python - 使用 Altair 对标准化堆积条形图进行排序

标签 python data-visualization altair

我正在尝试根据特定顺序对标准化堆积条形图进行排序。

我想要按此顺序排序的堆叠条:

Order = dict({'Paid work':1,'Education':2,'Sleep':3,'Other unpaid work':4,'Housework & Shopping':5,'Personal care':6, 'Eating and drinking':7,'TV and Radio':8,'Seeing friends':9,'Other leisures':10})

和国家/地区(Y 轴)也应按“付费工作”条的长度排序。

但我得到的是图表左端带有“电视和广播”的订单,无法看到哪个国家/地区的人们花在“有偿工作”上的时间最多。

我的尝试:

enter image description here

代码错误:

alt.Chart(df).mark_bar(size=15).encode(
    alt.Y('Country:O'),
    alt.X('Time:Q', stack='normalize',sort=alt.EncodingSortField(field='Order',order='descending')),
    
    alt.Color('Category:N',sort=alt.EncodingSortField(field='Order')),
    tooltip=['Country', 'Category', 'Time']
).properties(
    width=600,
    height=600, title = {'text' :'How do people spend their time?',
'subtitle' : 'Average of minutes per day from time-use diaries for people between 15 and 64'})

我是这个平台的新手,请看一下本笔记本中的数据和我的简单代码:https://www.kaggle.com/hoangyennhi/exercise-dv

最佳答案

如果您设置 sort alt.Color()中的参数到 'ascending''descending' ,它会自动对堆叠的条形进行排序:

import altair as alt
from vega_datasets import data

source = data.barley()

alt.Chart(source).mark_bar().encode(
    x='sum(yield)',
    y='variety',
    color=alt.Color('site', sort='descending'))

enter image description here

但是,当您指定自定义排序顺序时,它不会像现在这样not yet supported by Vega-Lite 。一个workaround was described in this comment ,其中提到您可以使用名为 color_<name-of-column>_sort_index 的特殊字段,根据颜色索引排序。在这个例子中,它看起来像这样:

site_order = ['Duluth', 'Crookston', 'Waseca', 'University Farm', 'Grand Rapids', 'Morris']
alt.Chart(source).mark_bar().encode(
    x='sum(yield)',
    y='variety',
    color=alt.Color('site', sort=site_order),
    order=alt.Order('color_site_sort_index:Q'))

enter image description here

关于python - 使用 Altair 对标准化堆积条形图进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66347857/

相关文章:

python - 平铺数据以创建 pandas 数据框

python signalR - 尝试连接时出现500服务器错误

python - Altair:如何根据最大值在面网格中对线条进行不同的样式设计?

python - 将词典保存到文件

Python - Bash - 随机数

python - 如何为 Altair 生成的图表添加副标题

python - 序列化和绘制 IP 地址的标准方法?

python - 如何制作跨列具有一致网格的分组条形图?

python - 更改 Jupyter 笔记本中 Altair 图渲染的大小

python - 在 Altair 中合并两个图例