在matplotlib中绘制条高度总和为1的直方图 [英] plotting histograms whose bar heights sum to 1 in matplotlib

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

问题描述

我想用一个使用matplotlib的矢量绘制一个归一化的直方图。我尝试了以下方法:

  plt.hist(myarray,normed = True)



以及:

  plt.hist( myarray,normed = 1)

但这两个选项都不会从[0,1]中产生y轴直方图的高度总和为1.我想生成这样的直方图 - 我该怎么做?



谢谢!

解决方案

如果你提出了一个更完整的工作(或者在这种情况下是非工作的)例子,它会更有帮助。 b

我尝试了以下方法:

  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,normed = True)
fig.canvas.draw()
plt.show()

这确实会产生一个条形图直方图,其y轴从 [0,1]

另外,根据 hist 文件(即 ax.hist? from ipython ),我认为总和也很好:

  * normed *:
如果* True *,则返回元组的第一个元素将是
是归一化形成概率密度的计数,即
``n /(len(x)* dbin)``。在概率密度中,直方图的
的积分应为1;您可以使用
梯形积分来验证概率密度函数::

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

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

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

按照预期,我得到的返回值为 1.0 。请记住, normed = True 并不意味着每个栏的值的总和将为1,而不是整个栏的整数为1。在我的情况下 np.sum(n)返回大约 7.2767


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

plt.hist(myarray, normed=True)

as well as:

plt.hist(myarray, normed=1)

but neither option produces a y-axis from [0, 1] such that the bar heights of the histogram sum to 1. I'd like to produce such a histogram -- how can I do it?

thanks!

解决方案

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

I tried the following:

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, normed=True)
fig.canvas.draw()
plt.show()

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

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))

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.

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

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