How to prevent alphabetical sorting for python bars with matplotlib?

前端 未结 2 509
忘了有多久
忘了有多久 2020-12-20 14:36

I\'m plotting some categorical data using a bar chart. Matplotlib keeps sorting my x-axis alphabetically even when I sort my dataframe values. Here\'s my code :



        
相关标签:
2条回答
  • 2020-12-20 15:01

    The issue

    This is a bug in matplotlib < 2.2.0 where the X axis is always sorted even if the values are strings. That is why the order of the bars is reversed in the following plot.

    x = ['foo', 'bar']
    y = [1, 2]
    plt.bar(x, y, color=['b', 'g'])
    

    The fix

    Upgrade matplotlib to 2.2.0 or higher. The same code produces the expected result with these versions.

    The workaround

    If you cannot or do not want to upgrade matplotlib you can use numbers instead of strings, then set the ticks and labels to the correct values:

    index = range(len(x))
    plt.bar(x, y, color=['b', 'g'])  # use numbers in the X axis.
    plt.xticks(index, x)  # set the X ticks and labels
    

    The Pandas way

    You can use Series.plot which might be convenient for you since your data is already in the form of a Series, but be aware that pandas plots things differently. Use the keyword argument rot to control the rotation of the labels.

    s = pd.Series(y, index=x)
    s.plot(kind='bar',rot=0, color=['b', 'g'])
    

    0 讨论(0)
  • 2020-12-20 15:20

    I answer my own question because I found a way around but it needs one more line of code to get to the same result and I don't like that :

    summary.plot(kind='bar', ax=new_ax, color=my_colors, width=0.8)
    fig3.autofmt_xdate(bottom=0.2, rotation=0, ha='center')
    

    Second line is needed because summary.plot() changes the orientation of the xticklabels to vertical...

    0 讨论(0)
提交回复
热议问题