我正在尝试使用altair
创建归一化的分组堆积条形图,并且正在努力使用标签。数据的格式为['A', 'B', 'C', 'D']
,其中A
是分组类别,B
是x
轴的值,C
是堆叠值,{ {1}}是值。我想创建一个如下图的图形:
我想通过此处的样式实现两个目标:
D
的组中只有一个x
标签,而不是在每个堆叠的组下方多次显示(Type (B)
次)。unique(A)
标签以包含x
的值,即将N
替换为Type 1
,将Type 1 (N=20)
替换为Type 2 (N=22)
等..,(N个值是根据下面的示例计算的)这里有一个最小的代码示例,可以重现该绘图的结果
Category 1
我尝试通过执行以下操作来使用import pandas
import altair as alt
def populate_data():
data = [
['Category 1', 'Type 1', True, 10],
['Category 1', 'Type 1', False, 5],
['Category 1', 'Type 1', 'V3', 5],
['Category 1', 'Type 2', True, 10],
['Category 1', 'Type 2', False, 8],
['Category 1', 'Type 2', 'V3', 4],
['Category 2', 'Type 1', True, 10],
['Category 2', 'Type 1', False, 5],
['Category 2', 'Type 1', 'V3', 5],
['Category 2', 'Type 2', True, 10],
['Category 2', 'Type 2', False, 8],
['Category 2', 'Type 2', 'V3', 4],
['Category 3', 'Type 1', True, 10],
['Category 3', 'Type 1', False, 5],
['Category 3', 'Type 1', 'V3', 5],
['Category 3', 'Type 2', True, 10],
['Category 3', 'Type 2', False, 8],
['Category 3', 'Type 2', 'V3', 4],
]
header = ['A', 'B', 'C', 'D']
df = pandas.DataFrame(data=data, columns=header)
return df
def plot_grouped_stacked_bars():
df = populate_data()
chart = alt.Chart(df).mark_bar().encode(
x=alt.X('B:N', axis=alt.Axis(title='Type (B)')),
y=alt.Y('D', axis=alt.Axis(grid=False, title='Percentage', format='%'), stack='normalize', sort="-x"),
column=alt.Column('A:N'),
color=alt.Color('C:N'),
)
chart.save('sample_plot.png')
plot_grouped_stacked_bars()
创建新的altair
层,并使用mark_text
和alt.layer()
层创建了一个新的chart
:
text
但收到错误消息text = alt.Chart(df).mark_text(dx=-15, dy=3, color='black').encode(
x=alt.X('B:N', axis=alt.Axis(title='Type B')),
y=alt.Y('D', axis=alt.Axis(grid=False, title='Percentage', format='%'), stack='normalize', sort="-x"),
column=alt.Column('A:N'),
text=alt.Text('B:N', format=' (N={%d})')
)
result = alt.layer(chart, text, data=df)
我觉得我raise ValueError("Faceted charts cannot be layered")
的用法对于分组的堆叠条不正确。对于显示如何实现结果的解释将非常赞赏。