gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:50:06 25 4
gpt4 key购买 nike

我正在尝试使用 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

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

最佳答案

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

关于python - 为什么创建分层条形图会删除排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58208319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com