我创建了一个 dictionary
来计算每个键在 list
中出现的次数,现在我想绘制其内容的直方图。
这是我要绘制的字典的内容:
{1: 27, 34: 1, 3: 72, 4: 62, 5: 33, 6: 36, 7: 20, 8: 12, 9: 9, 10: 6, 11: 5, 12: 8, 2: 74, 14: 4, 15: 3, 16: 1, 17: 1, 18: 1, 19: 1, 21: 1, 27: 2}
到目前为止,我写了这个:
import numpy as np
import matplotlib.pyplot as plt
pos = np.arange(len(myDictionary.keys()))
width = 1.0 # gives histogram aspect to the bar diagram
ax = plt.axes()
ax.set_xticks(pos + (width / 2))
ax.set_xticklabels(myDictionary.keys())
plt.bar(myDictionary.keys(), ******, width, color='g')
# ^^^^^^ what should I put here?
plt.show()
我只是简单地尝试了
plt.bar(myDictionary.keys(), myDictionary, width, color='g')
但这是结果:
我不知道为什么这 3 个条形图会移动,而且我希望直方图以有序的方式显示。
谁能告诉我怎么做?
最佳答案
您可以使用该函数绘制直方图,如下所示:
a = np.random.random_integers(0,10,20) #example list of values
plt.hist(a)
plt.show()
或者你可以像这样使用myDictionary
:
plt.bar(myDictionary.keys(), myDictionary.values(), width, color='g')
关于python - 从字典中绘制直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21195179/