Matplotlib曲线图直方图

时间:2019-01-30 22:57:39

标签: python python-3.x matplotlib histogram

我正在尝试显示扔一个公平骰子的概率密度的直方图。基本上应该有6个钢筋,每个钢筋的高度为1/6,等间距。我尝试过:

fair = np.array([1, 2, 3, 4, 5, 6]*100)
plt.hist(fair, density=True, label='Fair Die')
plt.show()

我也尝试过

plt.hist(fair, bins=11, density=True, label='Fair Die', align='mid')

但是它似乎不起作用。我不明白为什么hist命令默认情况下无法生成正确的直方图,它是如此简单。

2 个答案:

答案 0 :(得分:5)

这里的问题是垃圾箱。

您要避免将任何两个(或多个)值合并在一起,否则密度将是1/6的倍数。

以下是正确设置垃圾箱的方法:

fair = np.array([1, 2, 3, 4, 5, 6]*100)
plt.hist(fair, density=True, bins=[1,2,3,4,5,6,7], label='Fair Die', rwidth=0.9, align='left')  # rwidth is optional
plt.show()

来自the docs

  

bins:数组

     

垃圾箱的边缘。长度nbins + 1(nbins最后一个bin的左边缘和右边缘)。即使传入多个数据集,也始终是单个数组。

注意:如果要显示标签,请在plt.legend()之前致电plt.show()

注2:在这种情况下,建议设置rwidth 查看评论以了解它如何引起人们的困惑:P

或者,您可以在条形图周围绘制边框:

plt.hist(fair, density=True, bins=range(1,8), label='Fair Die', edgecolor='white', linewidth=1.2)

enter image description here

奖金:

如果您想拥有stochastic representation of your fair dice

fair_proba = np.random.random_integers(1,6, 1000) 

enter image description here

答案 1 :(得分:2)

In [10]: fair = np.array([1, 2, 3, 4, 5, 6]*100)
    ...: bins = np.array([i/2 for i in range(-1, 14)])
    ...: plt.hist(fair, bins=bins, label='Fair Die', align='left')
    ...: plt.xlim([0, 7])
    ...: plt.show()

enter image description here