在Python中按升序排序数据以显示柱状图

4 投票
1 回答
15425 浏览
提问于 2025-04-17 20:58

我有一堆数字,想把它们画成柱状图(像直方图那样)。

我已经把图画出来了,但它的顺序是我输入值的顺序,而不是从高到低的顺序,这正是我想要的。

这是我目前的代码:

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

但那并没有改变图的样子。提前谢谢大家!

1 个回答

6

首先对 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))

这样得到的结果是:

这里插入图片描述

撰写回答