max
max

Reputation: 4521

Order bar chart in Altair?

How can I order my bar chart so that it is in the order of greatest to least value? I tried the below code, but it isn't giving me the expected result.

I would like the bars ordered 'b', 'a', 'c' (by count)

df = pd.DataFrame([['a',2],['a',3],['b',4],['b',5],['b',4],['c',8]], columns=['Letters', 'Numbers'])

Letters Numbers
0   a   2
1   a   3
2   b   4
3   b   5
4   b   4
5   c   8

alt.Chart(df).mark_bar().encode(
   alt.X('Letters:N'),
   alt.Y('count():Q', sort=alt.EncodingSortField(field='count', op='count', order='ascending')))

Output chart

Upvotes: 16

Views: 20146

Answers (2)

Niels Hameleers
Niels Hameleers

Reputation: 1241

Simple alternative, specify the channel you'd like to sort by:

alt.Chart(df).mark_bar().encode(
   alt.X('Letters:N', sort='-y'),
   alt.Y('count():Q'))

From the documentation

Upvotes: 6

max
max

Reputation: 4521

The sort keyword needs to be applied to the axis being sorted - here it's the X axis.

alt.Chart(df).mark_bar().encode(
   alt.X('Letters:N', sort=alt.EncodingSortField(field="Letters", op="count", order='ascending')),
   alt.Y('count():Q'))

Upvotes: 18

Related Questions