如何在Altair中创建分组条形图?我正在尝试以下内容,但它只是并排生成两个图表。
Chart(data).mark_bar().encode(
column='Gender',
x='Genre',
y='Rating',
color='Gender'
)
组条形图的示例
我从Altair的文档中展示了Grouped Bar Chart的简化示例。您还可以查看完整的文档here。
基本上,你必须指定x轴Gender
(每个子图中的F或M),y轴指定为Rating
,Genre
指定为Column
。
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()