[英]Produce “dodged” or “side-by-side” bar/column charts in Altair?
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.抱歉,如果之前有人问过这个问题,但我正在寻找一种方法来使用 python 中的 Altair 库创建“躲避”的条形图(来自
ggplot2
的语言)。
I know Altair has this example :我知道 Altair 有这个例子:
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:这产生了这个 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).
理想情况下,我想要一个 plot ,其中成对的条形编码颜色的年份(蓝色是 1931 年,橙色是 1932 年),然后是沿 x 轴运行的城市(序数变量)。
Hard to explain, but here's an example of how to get a plot like this from seaborn (using different data; source is this SO question ):很难解释,但这里有一个如何从 seaborn 获得这样的 plot 的示例(使用不同的数据;来源是这个 SO question ):
Yes, you've found the recommended way to create grouped bar charts in Altair.是的,您已经找到了在 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:
这是您可以如何修改示例以使其更接近 seaborn 图表的方法:
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'
)
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!感谢 Jake 用他的回答为我指明了正确的方向!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.