Altair: Sort legend by data

Created on 10 Feb 2020  路  3Comments  路  Source: altair-viz/altair

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'} ? :)

data.txt

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'])
)
documentation question

Most helpful comment

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

visualization (55)

All 3 comments

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

visualization (55)

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

maxgerma picture maxgerma  路  3Comments

firasm picture firasm  路  3Comments

jtbaker picture jtbaker  路  3Comments

floringogianu picture floringogianu  路  3Comments

galloramiro picture galloramiro  路  3Comments