python - Matplotlib 绘制公平模具的直方图

标签 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 命令默认没有做出正确的直方图,就是这么简单的直方图。

最佳答案

这里的问题是垃圾箱。

您要避免将任何两个(或更多)值合并在一起,否则您的密度将是 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)

enter image description here

奖励:

如果你想要一个 stochastic representation of your fair dice :

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

enter image description here

关于python - Matplotlib 绘制公平模具的直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54450824/

相关文章:

python - 如何使用 python 链接到另一个目录?

python - 是我一个人还是 Windows 上新的 Python future 模块出现严重问题

django - 如何使用 ChannelNameRouter 在 Worker 和 Websocket(Django 和 Channels2.x)之间进行通信?

python - 使用类作为局部变量的容器对象替代Python中的 'nonlocal'

python - 使用补丁自定义散点图中的图例标记面部颜色

python - str.replace 在函数中不起作用

Python 将 .py 部分文件合并为一个 .py 文件

python-3.x - 简化 numpy 表达式

python - 如何使用python仅为特定列组合创建相关矩阵?

python - 如何使 3D 散点图颜色条调整到 Z 轴大小?