如何在直方图中绘制字典中的键和值

Dan*_*iel 3 python plot dictionary matplotlib

我需要用以下字典绘制直方图

x = {5:289, 8:341, 1:1565, 4:655, 2:1337, 9:226, 7:399, 3:967, 6:405}
Run Code Online (Sandbox Code Playgroud)

我需要第一个键从 1 到 9 排序。然后这些值将绘制在直方图中,显示最大概率为 1.0。我尝试了以下(以及其他内容)。

import matplotlib.pyplot as plt
import numpy as np

plt.hist(x.keys(), x.values(), color='g', label = "Real distribution")
plt.show()
Run Code Online (Sandbox Code Playgroud)

或者

plt.hist (x, bins = np.arange(9), color = 'g', label = "Real distribution")
plt.show()
Run Code Online (Sandbox Code Playgroud)

或者

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)
Run Code Online (Sandbox Code Playgroud)

Dav*_*idG 6

从您的评论来看,条形图似乎是显示数据的更好方式。

可以通过将字典的值除以值的总和来找到概率:

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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明