Search code examples
pythonmatplotlibbar-chartordereddict

Wrong order when setting xticks in matplotlib barplot


I'm trying to plot an OrderedDict using matplotlib. The dictionary d is sorted by value, in descending order:

OrderedDict([(1, 792), (2, 199), (3, 18), (4, 8), (8, 3), (5, 2), (10, 2), (6, 1), (9, 1)])

This is the code I'm using to draw the barplot:

fig, axs = plt.subplots(1)

axs.bar(d.keys(), d.values())
axs.set_xticks(list(d.keys()))
axs.set_yscale('log')

And this is the resulting plot:

enter image description here

In my idea the correct order for the x-axis labels is [1, 2, 3, 4, 8, 5, 10, 6, 9]. Why the bars are plotted in ascending order, instead?

Hon can I plot the bars following the same order of d?


Solution

  • Numerical values are sorted automatically when plot, which makes more sense. If you want to make sure you have the correct order, you can plot each bar manually:

    for i,k in enumerate(d.keys()):
        axs.bar(i, d[k])
    
    axs.set_xticks(range(len(d)))
    axs.set_xticklabels(d.keys())
    axs.set_yscale('log')
    

    Output:

    enter image description here

    Or you can turn the keys into string:

    axs.bar(list(map(str,d.keys()) ), d.values()) 
    axs.set_yscale('log')
    

    Output:

    enter image description here