python - Altair:设置原始颜色值会弄乱 SortField

标签 python pandas sorting altair

我正在尝试创建一个 Altair 条形图,其中条形按“计数”排序,然后应用 raw color values去酒吧。

import pandas as pd
import altair as alt

# Dummy data
df = pd.DataFrame({'fruit': ['apple', 'orange', 'blueberry', 'pear', 'grape', 'kiwi', 'strawberry', 'lychee'],
                  'count': [2, 4, 1, 7, 9, 12, 16, 35], 
                  'label': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'],
                  'colors': ['#4c78a8', '#f58518', '#e45756', '#72b7b2', '#54a24b', '#eeca3b', '#b279a2', 
                             '#9d755d']})

def make_alt_chart(df):
    g = alt.Chart(df).encode(
        x=alt.X('count'), 
        y=alt.Y('fruit', sort=alt.SortField(field='count', order='descending'))
    ).properties(
        width=700,
        height=650,
    )
    
    bars = g.mark_bar(
        size=60,
    ).encode(
        color=alt.Color('colors', sort=alt.SortField('count', order='descending'),
                        scale=None, legend=None)
    ).properties(height=alt.Step(75))

    text = g.mark_text(
        align='center',
        baseline='middle',
        dx=28
    ).encode(
        text='label'
    ).interactive()
    
    return (bars + text)

fruits = make_alt_chart(df)

fruits

sort=alt.SortField(field='count', order='descending') 添加到 y= 可以使图表按我想要的方式排序,但是当我添加 color=alt 时.Color('colors', sort=alt.SortField('count', order='descending'), scale=None, legend=None) 到 bar,y 轴上的顺序不再按“计数”。

这是运行上述代码后水果图表的样子: Fruits chart

这就是我想要的输出,但应用了自定义颜色: Sorted fruits chart without colors applied

如果有更简单的方法在 Altair 中设置自定义颜色,请告诉我。

注意:颜色十六进制值是 tableau10 方案,但去掉了粉红色阴影。

我已经查看了这些资源,但无法弄清楚:

最佳答案

如果您查看 Javascript 控制台,您会看到渲染器正在输出此警告:

WARN Domains that should be unioned has conflicting sort properties. Sort will be set to true.

相关Vega-Lite issue建议解决方法;替换

y=alt.Y('fruit', sort=alt.SortField(field='count', order='descending'))

y=alt.Y('fruit', sort=alt.EncodingSortField(field='count', order='descending', op='sum'))

这是结果: enter image description here

关于python - Altair:设置原始颜色值会弄乱 SortField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66896225/

相关文章:

python - 使用 Python 操作(非常)长的数据文件

Python Selenium Firefox 壁虎驱动程序。从终端分离浏览器

python - 使用 Python 和 Pandas 访问 JSON 元素

python - 拆分和编辑 CSV 列并按字母顺序排列

python - 滚动到 python selenium 中的特定元素

Python密码学包RSA——将私钥保存到DB

python - 当 HTML 表包含多个 <tbody> 标签时,让 pandas.read_html( ) 工作

python - 执行网格搜索后分配模型参数

python - 我可以在排序列表时使 python 代码工作吗

c++ - 对包含整数的文本文件进行排序,必须逐行进行排序