Altair:不对轴进行排序

时间:2018-06-28 01:07:45

标签: python bar-chart altair

以下是一些简单的示例代码,展示了我想解决的问题:

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数组中相同的顺序出现。我该怎么办?

1 个答案:

答案 0 :(得分:5)

您可以将列表传递到sort编码的alt.X属性,以控制类别的顺序。例如:

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'))
)

enter image description here