Produce “dodged” or “side-by-side” bar/column charts in Altair?

删除回忆录丶 提交于 2019-12-11 10:57:45

问题


Apologies if this has been asked before, but I'm looking for a way to create bar-charts that are "dodged" (language from ggplot2) using the Altair library in python.

I know Altair has this example:

import altair as alt
from vega_datasets import data

source = data.barley()

alt.Chart(source).mark_bar().encode(
    x='year:O',
    y='sum(yield):Q',
    color='year:N',
    column='site:N'
)

That produces this plot:

However, this has a lot of redundant labels and information. Ideally I want a plot where the paired bars encode the year in colour (blue is 1931 and orange is 1932) and then the cities running along the x-axis (ordinal variable).

Hard to explain, but here's an example of how to get a plot like this from seaborn (using different data; source isthis SO question):


回答1:


Yes, you've found the recommended way to create grouped bar charts in Altair. If you want to adjust the final look of the chart, you can do things like removing & rearranging labels and titles; here's how you might modify your example to make it closer to the seaborn chart:

import altair as alt
from vega_datasets import data

source = data.barley()

alt.Chart(source).mark_bar().encode(
    x=alt.X('year:O', axis=alt.Axis(title=None, labels=False, ticks=False)),
    y=alt.Y('sum(yield):Q', axis=alt.Axis(grid=False)),
    color='year:N',
    column=alt.Column('site:N', header=alt.Header(title=None, labelOrient='bottom'))
).configure_view(
    stroke='transparent'
)




回答2:


In case anyone ends up here through google etc, here's the code to bring the bars closer together:

import altair as alt
from vega_datasets import data

source = data.barley()

alt.Chart(source).mark_bar().encode(
    alt.X('year:O', axis=None),#axis=alt.Axis(title=None, labels=False, ticks=False)),
    alt.Y('sum(yield):Q', axis=alt.Axis(grid=True)),
    alt.Facet('site:N',title="Facet title Here",),
    color='year:N',
).properties(height=150, width=80).configure_view(
    stroke='transparent'
).configure_scale(bandPaddingInner=0,
                  bandPaddingOuter=0.1,
).configure_header(labelOrient='bottom',
                   labelPadding = 3).configure_facet(spacing=5
)

Result:

Thanks to Jake for pointing me in the right direction with his answer!



来源:https://stackoverflow.com/questions/58618197/produce-dodged-or-side-by-side-bar-column-charts-in-altair

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!