2

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

alvas
  • 115,346
  • 109
  • 446
  • 738
  • 1
    Why not reverse the axis properly? https://stackoverflow.com/questions/2051744/reverse-y-axis-in-pyplot Also prettyplotlib seems to have been abandoned for years and the dev suggests using seaborn instead. – Andras Deak -- Слава Україні Oct 05 '17 at 05:03
  • Ah... Yes, seaborn is much better maintained. – alvas Oct 05 '17 at 05:47
  • 1
    Note that while seaborn adds a lot of style functionality to matplotlib its main purpose is to easily interface with pandas. All seaborn styles are readily available from within matplotlib and unless you know what you are doing, I would recommend creating usual plots with matplotlib. – ImportanceOfBeingErnest Oct 05 '17 at 09:30

1 Answers1

2

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.