从字典绘制直方图 [英] Plot a histogram from a Dictionary

查看:544
本文介绍了从字典绘制直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个字典,它计算每个键的列表中的事件,现在我要绘制其内容的直方图。



这是我要绘制的字典的内容:

  {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,7,17​​,18,19,19,21:1,27:2} 

到目前为止,我写了:

  import numpy as np 
import matplotlib.pyplot as plt

pos = np.arange(len(myDictionary.keys()))
width = 1.0#给出直方图方面条形图

ax = plt.axes()
ax.set_xticks(pos +(width / 2))
ax.set_xticklabels(myDictionary.keys())

plt.bar(myDictionary.keys(),******,width,color ='g')
#^^^^^^我应该放在这里?
plt.show()

我只是简单地做了

  plt.bar(myDictionary.keys(),myDictionary,width,color ='g')
pre>

但这是结果:





我不知道为什么3个酒吧被移动,我也想直方图以有序的方式显示。



有人可以告诉我如何做吗?

解决方案

您可以使用该函数绘制直方图,如下所示:

  a = np.random。 random_integers(0,10,20)#example值列表
plt.hist(a)
plt.show()

或者您可以使用 myDictionary ,如下所示:

  plt.bar(myDictionary.keys(),myDictionary.values(),width,color ='g')


I created a dictionary that counts the occurrences in a list of every key and I would now like to plot the histogram of its content.

This is the content of the dictionary I want to plot:

{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}

So far I wrote this:

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

I tried by simply doing

plt.bar(myDictionary.keys(), myDictionary, width, color='g')

but this is the result:

and I don't know why the 3 bars are shifted and also I'd like the histogram to be displayed in a ordered fashion.

Can somebody tell me how to do it?

解决方案

You can use the function for plotting histograms like this:

a = np.random.random_integers(0,10,20) #example list of values
plt.hist(a)
plt.show()

Or you can use myDictionary just like this:

plt.bar(myDictionary.keys(), myDictionary.values(), width, color='g')

这篇关于从字典绘制直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆