python - 从字典中绘制直方图

标签 python dictionary matplotlib histogram

我创建了一个 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')

但这是结果:

enter image description here

我不知道为什么这 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/

相关文章:

python - 如何在 Django API 中一次更新多条记录(批量更新)

python - 尝试绘制任意 3d 函数的图形时出错

python - 使用来自另一个 Dataframe 的索引替换 Dataframe 中的行

python - 为什么 Python unicode 字符串需要对 UTF-8 BOM 进行特殊处理?

dictionary - 我在哪里可以获得用于检查拼写的字典文件?

c# - .NET:字典值是按引用还是按值存储的

javascript - 按添加元素的顺序遍历字典

python - 绘制python对象属性和对象存储在列表中

python - 如何用python绘制一个平行于x轴和z轴的平面?

python - 将 2D 数组复制到 3D 中/少一行 n 次