使用Altair修改归一化分组堆叠条形图中的x标签

时间:2020-05-13 01:22:56

标签: python pandas data-visualization altair

我正在尝试使用altair创建归一化的分组堆积条形图,并且正在努力使用标签。数据的格式为['A', 'B', 'C', 'D'],其中A是分组类别,Bx轴的值,C是堆叠值,{ {1}}是值。我想创建一个如下图的图形:

A normalized grouped stacked bar plot with labels but no counts

我想通过此处的样式实现两个目标:

  1. 确保在所有称为D的组中只有一个x标签,而不是在每个堆叠的组下方多次显示(Type (B)次)。
  2. 格式化每个组中的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_textalt.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")的用法对于分组的堆叠条不正确。对于显示如何实现结果的解释将非常赞赏。

0 个答案:

没有答案