我需要用下面的字典绘制一个直方图
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)发布于 2017-12-11 17:06:42
从您的评论来看,条形图似乎是显示数据的更好方式。
概率可以通过将字典的值除以这些值的和来得到:
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()

发布于 2017-12-08 08:38:30
打印前对数据进行排序:
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()

发布于 2017-12-08 09:08:14
我为我的代码有多么可怕的非pythonic和怪异而提前道歉。我不太擅长数学作图和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()https://stackoverflow.com/questions/47705972
复制相似问题