Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

python - Plot a histogram from a Dictionary

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:

enter image description here

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...