绘制直方图,使条形高度总和为 1(概率) [英] Plot a histogram such that bar heights sum to 1 (probability)

查看:40
本文介绍了绘制直方图,使条形高度总和为 1(概率)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 matplotlib 从向量绘制归一化直方图.我尝试了以下方法:

I'd like to plot a normalized histogram from a vector using matplotlib. I tried the following:

plt.hist(myarray, normed=True)

以及:

plt.hist(myarray, normed=1)

但两个选项都不会从 [0, 1] 生成 y 轴,使得直方图的条形高度总和为 1.

but neither option produces a y-axis from [0, 1] such that the bar heights of the histogram sum to 1.

推荐答案

如果您提出一个更完整的工作(或在本例中为非工作)示例会更有帮助.

It would be more helpful if you posed a more complete working (or in this case non-working) example.

我尝试了以下方法:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.randn(1000)

fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, rectangles = ax.hist(x, 50, density=True)
fig.canvas.draw()
plt.show()

这确实会生成一个条形图直方图,其 y 轴来自 [0,1].

This will indeed produce a bar-chart histogram with a y-axis that goes from [0,1].

此外,根据 hist 文档(即来自 ipythonax.hist?),我认为总和也很好:

Further, as per the hist documentation (i.e. ax.hist? from ipython), I think the sum is fine too:

*normed*:
If *True*, the first element of the return tuple will
be the counts normalized to form a probability density, i.e.,
``n/(len(x)*dbin)``.  In a probability density, the integral of
the histogram should be 1; you can verify that with a
trapezoidal integration of the probability density function::

    pdf, bins, patches = ax.hist(...)
    print np.sum(pdf * np.diff(bins))

在上面的命令之后尝试一下:

Giving this a try after the commands above:

np.sum(n * np.diff(bins))

我按预期得到 1.0 的返回值.请记住,normed=True 并不意味着每个柱上的值的总和是统一的,而是柱上的积分是统一的.在我的例子中 np.sum(n) 返回了大约 7.2767.

I get a return value of 1.0 as expected. Remember that normed=True doesn't mean that the sum of the value at each bar will be unity, but rather than the integral over the bars is unity. In my case np.sum(n) returned approx 7.2767.

这篇关于绘制直方图,使条形高度总和为 1(概率)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆