Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 379
ericg Avatar asked Jun 28 '18 01:06

ericg


1 Answers

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

enter image description here

like image 74
jakevdp Avatar answered Nov 06 '22 12:11

jakevdp