Search code examples
pythonmatplotlibplotprettyplotlib

Order of bars in prettyplotlib barchart


How to control the order of the bars in prettyplotlib barchart?

From prettyplotlib==0.1.7

Using the standard ppl.bar I could get a barchart as such:

%matplotlib inline
import numpy as np
import prettyplotlib as ppl
import matplotlib.pyplot as plt

fig, ax = plt.subplots(1)

counter = {1:1, 2:4, 3:9, 4:16, 5:25, 6:36, 7:49}

x, y = zip(*counter.items())

ppl.bar(ax, x , y, annotate=True, grid='y')

enter image description here

But if I want to reverse the x-axis bars,when I change the x list, the order of bars reversed but not the labels:

ppl.bar(ax, list(reversed(x)) , y, annotate=True, grid='y')

enter image description here

I could use the xticklabels argument:

ppl.bar(ax, list(reversed(x)) , y, annotate=True, xticklabels=list('7654321'), grid='y')

But that didn't work too, it returns the same right bar order, wrong x-axis labels:

enter image description here

Strangely, when I reverse the list of the xticklabels,

 ppl.bar(ax, list(reversed(x)) , y, annotate=True, xticklabels=list('1234567'), grid='y')

I've got what I needed but it's strange now that the x list is reversed but the xticklabels are not...

enter image description here

But if I removed the reversed on the x list:

ppl.bar(ax, x , y, annotate=True, xticklabels=list('1234567'), grid='y')

we get the first same graph as ppl.bar(ax, x , y, annotate=True, grid='y')...

enter image description here


Solution

  • Since prettyplotlib is mostly responsible for the style, your problem is actually not specific to its use, and you need to use native matplotlib methods to reverse your x axis:

    import numpy as np
    import prettyplotlib as ppl
    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots(1)
    
    counter = {1:1, 2:4, 3:9, 4:16, 5:25, 6:36, 7:49}
    
    x, y = zip(*counter.items())
    
    ppl.bar(ax, x , y, annotate=True, grid='y')
    ax.invert_xaxis() # <-- fix
    

    The result is exactly what you need: both plot and labels are reversed:

    pretty result

    This is also the semantically correct approach to your problem: your data is still the same, you only want it to be represented differently.