Altair:不对轴进行排序

Altair: not sorting an axis

下面是一些简单的示例代码,演示了我要解决的问题:

import pandas as pd
import altair as alt

categoryNames    = [ 'a', 'f', 'r', 'u', 'p' ]
categories       = pd.Series( categoryNames )
categories.index = categoryNames

amountsRaw       = [ 50, -100, 75, 100, -500 ]
amounts          = pd.Series( amountsRaw )
amounts.index    = categoryNames

df = pd.DataFrame( { "Amounts" : amounts, "Categories" : categories } )

alt.Chart( df ).mark_bar().encode(
    x='Categories',
    y='Amounts',
    color = alt.condition( alt.datum.Amounts > 0, alt.value( 'green' ), alt.value( 'red' ) )
)

这将生成一个条形图,但我不想对 x 轴类别进行排序。它们需要以与在 categoryNames 数组中相同的顺序出现。我该怎么做?

你可以传递一个列表给alt.X编码的sort属性来控制分类的顺序。例如:

alt.Chart(df).mark_bar().encode(
    x=alt.X('Categories', sort=categoryNames),
    y='Amounts',
    color=alt.condition(alt.datum.Amounts > 0, alt.value('green'), alt.value('red'))
)