如何在Matplotlib中绘制直方图,以使条形的高度总和为1? [英] How can I plot a histogram such that the heights of the bars sum to 1 in matplotlib?

查看:119
本文介绍了如何在Matplotlib中绘制直方图,以使条形的高度总和为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. I'd like to produce such a histogram -- how can I do it?

推荐答案

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

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文档(即ipython中的ax.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.

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

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