Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 235
max Avatar asked Oct 18 '18 15:10

max


People also ask

How do I change the order of bars in a bar graph?

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.

How do I change the order of my bar?

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.


2 Answers

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

like image 179
Niels Hameleers Avatar answered Oct 19 '22 08:10

Niels Hameleers


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'))
like image 28
max Avatar answered Oct 19 '22 08:10

max