Plot a dataframe with values sorted

tmp = df.groupby("someCol")["someOtherCol"].mean().sort_values()
st.dataframe(tmp)  # (1)
st.bar_chart(tmp)  # (2)

The dataframe (well technically a Series) in (1) is rendered correctly and the values are ordered. But, the plot is ordered by the lexicographic order of the index (i.e. the values in someCol). How can I control this?

Hi @drorata, welcome to the forum! We implement bar_chart with Altair with the following spec:

    chart = (
        getattr(alt.Chart(data), "mark_" + chart_type)()
        .encode(
            alt.X("index", title=""),
            alt.Y("value", title=""),
            alt.Color("variable", title="", type="nominal"),
            alt.Tooltip(["index", "value", "variable"]),
            opacity=opacity,
        )
        .interactive()

where chart_type is "bar"
You can find this in https://github.com/streamlit/streamlit/blob/develop/lib/streamlit/elements/altair.py#L52

You can use altair directly with

st.altair_chart(chart)

and you can customize chart as you want by following the Altair spec. I don’t have your dataset, but this SortedBarChart example may be what you are looking for: https://altair-viz.github.io/gallery/bar_chart_sorted.html

Hope this helps.

Best,

Matteo

1 Like