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.
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)
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"
)
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