如何在 Altair 中创建分组条形图?

How to create a grouped bar chart in Altair?

如何在 Altair 中创建分组条形图?我正在尝试以下操作,但它只是并排生成两个图表。

Chart(data).mark_bar().encode(
   column='Gender',
   x='Genre',
   y='Rating',
   color='Gender'
)

组条形图示例

我展示了一个简化的例子Grouped Bar Chart from Altair's documentation. You can also see the full documentation here

基本上,您必须指定 x 轴 Gender(每个子图中的 F 或 M),y 轴为 RatingGenreColumn

from altair import *
import pandas as pd

# create dataframe
df = pd.DataFrame([['Action', 5, 'F'], 
                   ['Crime', 10, 'F'], 
                   ['Action', 3, 'M'], 
                   ['Crime', 9, 'M']], 
                  columns=['Genre', 'Rating', 'Gender'])

chart = Chart(df).mark_bar().encode(
   column=Column('Genre'),
   x=X('Gender'),
   y=Y('Rating'),
   color=Color('Gender', scale=Scale(range=['#EA98D2', '#659CCA']))
).configure_facet_cell(
    strokeWidth=0.0,
)

chart.display() # will show the plot

条形图如下所示

添加轴参数

您只需遵循文档中的 Axis 参数即可使绘图看起来更漂亮:

chart = Chart(df).mark_bar().encode(
   column=Column('Genre', 
                 axis=Axis(axisWidth=1.0, offset=-8.0, orient='bottom'),
                 scale=Scale(padding=4.0)),
   x=X('Gender', axis=False),
   y=Y('Rating', axis=Axis(grid=False)),
   color=Color('Gender', scale=Scale(range=['#EA98D2', '#659CCA']))
).configure_facet_cell(
    strokeWidth=0.0,
)

chart.display()

如果您在较新版本的 Altair(自 4.2.0 起)上尝试接受的答案。你会注意到它不起作用。一些 API 已经改变,所以要在 Altair 4.2.0 中获得相同的结果,您可以使用我对 的回答中发布的方法。对于 Altair 的开发版本(可能会发布为 5.0),这变得更容易实现,因为您可以像这样使用 xOffset 编码而无需对图表进行分面:

import altair as alt
import pandas as pd

df = pd.DataFrame([['Action', 5, 'F'], 
                   ['Crime', 10, 'F'], 
                   ['Action', 3, 'M'], 
                   ['Crime', 9, 'M']], 
                  columns=['Genre', 'Rating', 'Gender'])

chart = alt.Chart(df).mark_bar().encode(
   x=alt.X('Genre', axis=alt.Axis(labelAngle=0)),
   xOffset='Gender',
   y=alt.Y('Rating', axis=alt.Axis(grid=False)),
   color='Gender'
).configure_view(
    stroke=None,
)

chart