【问题标题】:Sort data to present barchart highest to lowest in python对数据进行排序以在python中从最高到最低显示条形图
【发布时间】:2014-04-07 22:01:53
【问题描述】:

我有一堆出现的数字,想将它们绘制成条形图(如直方图)。

我的图表工作正常,但它是按照我输入值的顺序,而不是我想要的从高到低的顺序。

这是目前为止的代码:

 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()

它会生成以下图片。抱歉,标签都被弄脏了。

我希望它从最高到最低...有谁知道我如何在不改变我的现象的情况下做到这一点?我试过做

phenos.sort()

在我绘制图表之前,但这并没有改变图表。提前致谢!

【问题讨论】:

标签: python matplotlib


【解决方案1】:

先排序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)

c.sort(key=itemgetter(0))

得到:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多