我需要使用以下字典绘制直方图
x = {5:289, 8:341, 1:1565, 4:655, 2:1337, 9:226, 7:399, 3:967, 6:405}
我需要从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()
或
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)
答案 0 :(得分:2)
在绘图前对数据进行排序:
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}
new_x = sorted(x.items(), key=lambda x:x[0])
plt.hist([i[-1] for i in new_x], normed=True, bins=len(new_x), color='g', label = "Real distribution")
plt.show()
答案 1 :(得分:1)
从您的评论中,似乎条形图是显示数据的更好方式。
可以通过将字典的值除以值的总和来找到概率:
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()
答案 2 :(得分:0)
我提前抱歉我的代码非常恐怖和奇怪。我对mathplot或numpy不太强。
如果您使用the_keys = list(set(dict.keys()))
获取一组密钥(已订购,因为它是一套。就像我在评论中说的那样,我在这里做了一些非常难看的黑客攻击。)然后你可以做the_values = [x[i] for i in the_keys]
获取按键排序的字典的列表表示。然后用
plt.hist(the_keys, the_values, color='g', label = "Real distribution")
plt.show()