如何在直方图中绘制字典中的键和值 [英] How to plot keys and values from dictionary in histogram
本文介绍了如何在直方图中绘制字典中的键和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要用以下字典绘制直方图
I need to plot a histogram with the following dictionary
x = {5:289, 8:341, 1:1565, 4:655, 2:1337, 9:226, 7:399, 3:967, 6:405}
我首先需要将键从1到9排序.然后将这些值绘制在直方图中,最大概率为1.0.我已经尝试了以下方法(以及其他方法).
I need first keys be ordered from 1 to 9. Then the values will be plotted in the histogram, showing a maximum probability of 1.0. I have tried the following (plus other stuff).
import matplotlib.pyplot as plt
import numpy as np
plt.hist(x.keys(), x.values(), color='g', label = "Real distribution")
plt.show()
或
plt.hist (x, bins = np.arange(9), color = 'g', label = "Real distribution")
plt.show()
或
fsn_count_ = sorted(fsn_count)
plt.hist (fsn_count_, bins = np.arange(9), color = 'b', label = "Real distribution")
plt.plot ([0] + bf, color = 'g', label = "Benford Model")
plt.xlabel ('Significant number')
plt.ylabel ('Percentage')
plt.xlim (1,9)
plt.ylim (0,1)
plt.legend (bbox_to_anchor = (1, 1), loc="upper right", borderaxespad=0.)
plt.savefig (country_ + '.png')
plt.show ()
plt.clf ()
distribution_sum = sum(bf)
print('The sum of percentage distribution is:', distribution_sum)
推荐答案
从您的评论看来,条形图似乎是显示数据的更好方法.
From your comment, it seems that a bar chart would be a better way to display the data.
可以通过将字典的值除以值的总和来找到概率:
The probability can be found by dividing the values of the dictionary by the sum of the values:
import matplotlib.pyplot as plt
import numpy as np
x = {5:289, 8:341, 1:1565, 4:655, 2:1337, 9:226, 7:399, 3:967, 6:405}
keys = x.keys()
vals = x.values()
plt.bar(keys, np.divide(list(vals), sum(vals)), label="Real distribution")
plt.ylim(0,1)
plt.ylabel ('Percentage')
plt.xlabel ('Significant number')
plt.xticks(list(keys))
plt.legend (bbox_to_anchor=(1, 1), loc="upper right", borderaxespad=0.)
plt.show()
这篇关于如何在直方图中绘制字典中的键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文