Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Altair stacked area with custom sorting

Tags:

python

altair

How can I specify a custom order (i.e. list of strings) for sorting of a stacked area chart?

I would like to sort the areas in the order ['B', 'A', 'C'] from lowest to highest on the chart, regardless of value. I looked at the documentation for alt.Order but that appears to be based on aggregations, rather than a fixed custom order.

enter image description here

import altair as alt
import pandas as pd

df = pd.DataFrame(
    {'A': range(0,10),
    'B': range(0,20,2),
     'C': range(0,30,3)
    },
)
df['date'] = range(0,10)
df = df.melt(id_vars='date')

chart = alt.Chart(df).mark_area().encode(
    x="date",
    y=alt.Y("value:Q", stack='zero'),
    color="variable",
)
display(chart)
like image 300
ac24 Avatar asked Oct 16 '25 10:10

ac24


1 Answers

You can do this using the order channel, and a transform to compute the desired order. It's also helpful to adjust the sort property of the legend so that it matches the stack order:

alt.Chart(df).transform_calculate(
    order="{'B':0, 'A': 1, 'C': 2}[datum.variable]"  
).mark_area().encode(
    x="date",
    y=alt.Y("value:Q", stack='zero'),
    color=alt.Color("variable", sort=alt.SortField("order", "descending")),
    order="order:O"
)

enter image description here

like image 86
jakevdp Avatar answered Oct 17 '25 23:10

jakevdp