排序数据以在python中显示从高到低的条形图 [英] Sort data to present barchart highest to lowest in python
问题描述
我有一堆数字,想将它们绘制在条形图(如直方图)中.
I've got a bunch of occurances of numbers and want to plot them in a bar chart (like a histogram).
我已经使图表正常工作,但是它是按我在值中键入的顺序,而不是我想要的从最高到最低的顺序.
I've got the chart working, but it is in the order I typed in the values, not the order of highest to lowest, which is what I want.
这是到目前为止的代码:
Here is the code so far:
phenos = [128, 20, 0, 144, 4, 16, 160, 136, 192, 52, 128, 20, 0, 4, 16, 144, 130, 136, 132, 22,
128, 160, 4, 0, 32, 36, 132, 136, 164, 130, 128, 22, 4, 0, 144, 160, 54, 130, 178, 132,
128, 4, 0, 136, 132, 68, 196, 130, 192, 8, 128, 4, 0, 20, 22, 132, 144, 192, 130, 2,
128, 4, 0, 132, 20, 136, 144, 192, 64, 130, 128, 4, 0, 144, 132, 28, 192, 20, 16, 136,
128, 6, 4, 134, 0, 130, 160, 132, 192, 2, 128, 4, 0, 132, 68, 160, 192, 36, 64,
128, 4, 0, 136, 192, 8, 160, 12, 36, 128, 4, 0, 22, 20, 144, 86, 132, 82, 160,
128, 4, 0, 132, 20, 192, 144, 160, 68, 64, 128, 4, 0, 132, 160, 144, 136, 192, 68, 20]
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
labels, values = zip(*Counter(phenos).items())
indexes = np.arange(len(labels))
width = 1
plt.bar(indexes, values, width)
plt.xticks(indexes + width * 0.5, labels)
plt.show()
它产生以下图片.对不起,标签都被弄脏了.
It produces the following picture. Sorry the labels are all smushed.
我希望它从最高变到最低...有人知道我可以在不改变我的现象的情况下做到这一点吗?我尝试过
I want it to go from highest to lowest... does anyone know how I can do that without changing my phenos? I tried doing
phenos.sort()
在我绘制图形之前,但这并没有改变图形.提前致谢!
before I drew the graph but that did not change the graph. Thanks in advance!
推荐答案
首先将 Counter(phenos).items()
排序:
In [40]: from collections import Counter
...: import numpy as np
...: import matplotlib.pyplot as plt
...: from operator import itemgetter
...:
...: c = Counter(phenos).items()
...: c.sort(key=itemgetter(1))
...: labels, values = zip(*c)
...:
...: indexes = np.arange(len(labels))
...: width = 1
...:
...: plt.bar(indexes, values, width)
...: plt.xticks(indexes + width * 0.5, labels)
...: plt.show()
<小时>
输出:
或者如果你想按 x 轴排序,只需使用 itemgetter(0)
:
Or if you wanna sort by the x-axis, just use itemgetter(0)
:
c.sort(key=itemgetter(0))
得到:
这篇关于排序数据以在python中显示从高到低的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!