为什么创建分层条形图会删除排序?

时间:2019-10-02 19:39:24

标签: python altair

我正在尝试使用Altair创建堆积的条形图。我想用降序排列所有条形的百分比来标记每个条形。这是我创建两层的方法(一层用于条形,一层用于标签):

import pandas as pd
import altair as alt

df1 = pd.DataFrame({'a': list('AAAABBBB'),
                    'b': list('xxyyxxyy'),
                    'c': [2, 7, 4, 1, 2, 6, 8, 4]})

df2 = df1.groupby('a', as_index=False).sum()
df2['pct'] = (df2['c'] / df2['c'].sum()).round(2)

bars = alt.Chart(df1).mark_bar().encode(
    x=alt.X('c', scale=alt.Scale(domain=[0, 22])),
    y=alt.Y('a', sort=alt.EncodingSortField(field='c', order='descending')),
    color='b',
)
text = alt.Chart(df2).mark_text(dx=15).encode(
    x='c',
    y=alt.Y('a', sort=alt.EncodingSortField(field='c', order='descending')),
    text='c'
)

每一层都以正确的顺序排序,看起来不错。但是当我组合它们时,排序将重置,并且它们不再降序排序。

both = bars + text
both

bar chart in wrong order

在合并图层时如何保持条形排序?

1 个答案:

答案 0 :(得分:2)

Vega-Lite不支持对联合域进行排序。如果打开图表的JavaScript控制台,或者view it in the vega editor,您将看到Vega-Lite产生的警告:

[Warning] Dropping sort property {"field":"c","op":"sum","order":"descending"} as unioned domains only support boolean or op "count".
[Warning] Dropping sort property {"field":"c","op":"mean","order":"descending"} as unioned domains only support boolean or op "count".

相关的Vega-Lite错误在这里:https://github.com/vega/vega-lite/issues/5048

如果您从同一数据集构建两个图层,则可以避免这种情况;例如:

bars = alt.Chart(df1).mark_bar().encode(
    x=alt.X('c:Q', scale=alt.Scale(domain=[0, 22])),
    y=alt.Y('a:N', sort=alt.EncodingSortField(field='c', op='sum', order='descending')),
    color='b:N',
)

text = alt.Chart(df1).mark_text(dx=15).encode(
    x='sum(c):Q',
    y=alt.Y('a:N', sort=alt.EncodingSortField(field='c', op='sum', order='descending')),
    text=alt.Text('sum(c):Q')
)

bars + text

enter image description here