I would like to auto sort the legend, to be in the same order as the chart data. Doesn't have to be perfect; but not that the top line chart, is the bottom legend item.
Below I did this manually, but this is a pain with a lot of categories.
There seems to be a 'sort field definition', but the documentation jumps to Vega spec (of which I am unsure how to apply within Altair).
https://altair-viz.github.io/user_guide/generated/core/altair.Color.html#altair.Color
https://vega.github.io/vega-lite/docs/sort.html#sort-field
Something like: sort={'category': 'value_count'} ? :)
import pandas as pd
import altair as alt
df = pd.read_csv("data.txt", parse_dates=['date'])
alt.Chart(df).mark_line().encode(
x='date',
y='count',
color=alt.Color('category',
sort=['cat2', 'cat3', 'cat1'])
)
You can do this with an appropriately constructed EncodingSortField:
import pandas as pd
import altair as alt
df = pd.read_csv("data.txt", parse_dates=['date'])
alt.Chart(df).mark_line().encode(
x='date',
y='count',
color=alt.Color('category',
sort=alt.EncodingSortField('count', op='mean', order='descending'))
)

Thanks Jake, that works great!
Would it be helpful if I added a this as an example/reference to the documentation page?
https://altair-viz.github.io/user_guide/generated/core/altair.Color.html#altair.Color
Reference: https://altair-viz.github.io/user_guide/generated/core/altair.EncodingSortField.html#altair.EncodingSortField
If so, please point out to me where to update the documentation page.
Is it in the GitHub repro, as I haven't been able to locate the page source yet
Yes, documentation updates are always welcome! The documentation source can be found here: https://github.com/altair-viz/altair/tree/master/doc
Unfortunately we don't currently have any instructions on updating the docs. Let me know if you have questions.
Note that both pages you linked to are automatically generated by sphinx auto-doc, so those aren't the parts of the docs that can be modified. You can more easily modify any of the source files in https://github.com/altair-viz/altair/tree/master/doc/user_guide
Most helpful comment
You can do this with an appropriately constructed
EncodingSortField: