Matplotlib fair di直方图

2024-05-23 19:08:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着显示一个掷骰子概率密度的直方图。基本上应该有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命令在默认情况下不能生成正确的直方图,它是如此简单的直方图。你知道吗


Tags: true高度fairnpplt直方图densityarray
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

这里的问题是垃圾箱。你知道吗

您希望避免将任何两个(或更多)值组合在一起,否则密度将是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,否则在bins之间没有空间,这里所有的bis都具有相同的维度,因此都显示为单个块。看看评论,看看这是如何让人困惑的: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

相关问题 更多 >