我正在尝试显示掷出公平骰子的概率密度的直方图。基本上应该有 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 命令默认没有做出正确的直方图,就是这么简单的直方图。
这里的问题是垃圾箱。
您要避免将任何两个(或更多)值合并在一起,否则您的密度将是 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 : array
The edges of the bins. Length nbins + 1 (nbins left edges and right edge of last bin). Always a single array even when multiple data sets are passed in.
注意:如果要显示标签,请在 plt.show()
之前调用 plt.legend()
。
注意 2:在这种情况下,建议设置 rwidth
< binsize,否则 bin 之间没有空间,并且这里所有 bis 的维度相同,因此它们都显示为单个 block . 看看评论,看看这让人们感到困惑:P
或者,您可以在条形图周围画一个边框:
plt.hist(fair, density=True, bins=range(1,8), label='Fair Die', edgecolor='white', linewidth=1.2)
奖励:
如果你想要一个 stochastic representation of your fair dice :
fair_proba = np.random.random_integers(1,6, 1000)