简体   繁体   中英

Altair: not sorting an axis

Here is some simple sample code demonstrating the problem I would like to solve:

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

This will produce a bar chart, but I do not want the x-axis categories sorted. They need to appear in the same order as they do in the categoryNames array. How can I do that?

You can pass a list to the sort property of the alt.X encoding to control the order of the categories. For example:

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM