如何控制prettyplotlib条形图中条形的顺序?
来自prettyplotlib==0.1.7
使用标准的 ppl.bar 我可以获得这样的条形图:
%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')
但是如果我想反转 x 轴条,当我更改 x 列表时,条的顺序会反转但标签不会:
ppl.bar(ax, list(reversed(x)) , y, annotate=True, grid='y')
我可以使用 xticklabels 参数:
ppl.bar(ax, list(reversed(x)) , y, annotate=True, xticklabels=list('7654321'), grid='y')
但这也不起作用,它返回相同的正确条形顺序,错误的 x 轴标签:
奇怪的是,当我反转 xticklabels 的列表时,
ppl.bar(ax, list(reversed(x)) , y, annotate=True, xticklabels=list('1234567'), grid='y')
我已经得到了我需要的东西,但是很奇怪现在 x 列表被颠倒了,但是 xticklabels 不是......
但是如果我删除 x 列表中的 reversed :
ppl.bar(ax, x , y, annotate=True, xticklabels=list('1234567'), grid='y')
我们得到与 ppl.bar(ax, x , y, annotate=True, grid='y')...
请您参考如下方法:
由于 prettyplotlib 主要负责样式,您的问题实际上并不特定于它的使用,您需要使用 native matplotlib 方法来反转 x 轴:
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
结果正是您所需要的:绘图和标签都颠倒了:
这也是解决您的问题的语义正确方法:您的数据仍然相同,您只是希望它以不同的方式表示。
