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')))
Under Chart Tools, on the Design tab, in the Data group, click Select Data. In the Select Data Source dialog box, in the Legend Entries (Series) box, click the data series that you want to change the order of. Click the Move Up or Move Down arrows to move the data series to the position that you want.
The reorder function is used here to change the order of the graphs. Here if you want ascending order then you'll use '+' plus sign, if you want in descending order then you should use '-' minus sign. Note: Column2 must be the column with numeric data. Example: Let us first show the same bar plot in ascending order.
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
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'))
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