Plot a histogram from a Dictionary

一笑奈何 提交于 2019-11-28 05:53:38

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')
Franck Dernoncourt

With Python 3 you need to use list(your_dict.keys()) instead of your_dict.keys() (otherwise you get TypeError: 'dict_keys' object does not support indexing):

import matplotlib.pyplot as plt

dictionary = {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}
plt.bar(list(dictionary.keys()), dictionary.values(), color='g')
plt.show()

Tested with Matplotlib 2.0.0 and python 3.5.

FYI: Plotting a python dict in order of key values

values = [] #in same order as traversing keys
keys = [] #also needed to preserve order
for key in myDictionary.keys():
  keys.append(key)
  values.append(myDictionary[key])

Use 'keys' and 'values'. This ensures that the order is preserved.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!