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'))
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With