【问题标题】:matplotlib.pyplot.hist wrong normed property [duplicate]matplotlib.pyplot.hist 错误的规范属性 [重复]
【发布时间】:2019-04-03 10:21:26
【问题描述】:

我正在创建以数据框形式组织并按天分组的数据直方图。在某些日子里,数据可能完全为空。因此,当我使用normed = True 属性绘制直方图时,我希望有一个以零为中心且高度等于 1 的单个 bin。但是,我看到高度等于 bin 的数量。我怎样才能解决这个问题?我想用直方图表示一个概率密度函数,所以最大值应该是1。

代码示例和输出:

plt.rcParams['figure.figsize'] = 10, 4
data = np.zeros((1000))
l = plt.hist(data,normed = True, bins = 100)

编辑:我现在看到属性normed 已被弃用。但是,如果我尝试使用属性density,则会收到错误AttributeError: Unknown property density

【问题讨论】:

  • 你用的是什么版本的matplotlib?
  • 无论如何,如果您阅读文档,density 参数不会给您想要的 - “直方图下的面积(或积分)总和为 1”(除非您更改当然是垃圾箱)
  • 我使用的是 2.0.2 版
  • 特别是this重复的答案
  • area=1 由density=True 自动给出。你想要的是面积和高度=1。我不认为有那么多的定制是可用的

标签: python matplotlib plot histogram


【解决方案1】:

您看到的图是正确的,因为曲线下的面积(直方图/条形图)应该是 1。您的图中确实是这种情况。为了突出这一点,我在x=0.01 创建了一条垂直线,您会注意到条形的宽度确实是 0.01。由于条形高度为 100,因此面积为 100 * 0.01 = 1。

plt.rcParams['figure.figsize'] = 10, 4
data = np.zeros((1000))
l = plt.hist(data,normed = True, bins = 100)
plt.axvline(0.01, lw=1)
plt.ylim(0, 150)

如果你使用density=True as 也会发生同样的情况

l = plt.hist(data,density = True, bins = 100)

使用jdehesa的建议,按照你的方式进行

l = plt.hist(data,density = True, bins=np.arange(-10, 11))

使用基于this 答案的DavidG 的建议,您的高度为1,但该区域未标准化为1。

weights = np.ones_like(data)/float(len(data))
l = plt.hist(data,weights=weights)

最后,如果您需要高度为 1 和宽度为 1(因此面积 = 1)以及归一化面积,则可以使用单个 bin 作为

l = plt.hist(data, density=True, bins=1)
plt.xlim(-10, 10)

【讨论】:

  • 我明白了。如何将最大值设为 1?我想使用hist 命令绘制概率密度函数
  • 要使最大值为 1,您需要bins=1。在这种情况下,您的 bin 宽度将为 1,bin 高度为 1,因此面积将为 1*1 = 1。如果您使用bins=10,则高度将为 10,但宽度将变为 0.1,因此面积 = 10 * 0.1 = 1
  • 您不需要设置 bins=1,只需确保 bin 的宽度至少为 1。要获得落在每个 bin 上的样本分数图,您可以使用 bin宽度正好为 1(例如 bins=np.arange(-10, 11))。
  • @jdehesa:感谢您的评论。我在回答中包含了您的建议。
【解决方案2】:

正如其他人所解释的那样,normed=True(或最新版本的 Matplotlib 中的density=True)使直方图下的面积等于 1。您可以得到一个直方图,它表示落在每个 bin 上的样本比例,如下所示:

import matplotlib.pyplot as plt
import numpy as np

data = np.zeros((1000))
# Compute histogram
hist, bins = np.histogram(data, density=True, bins=100)
# Width of each bin
bins_w = np.diff(bins)
# Compute proportion of sample in each bin
hist_p = hist * bins_w
# Plot histogram
plt.bar(bins[:-1], hist_p, width=bins_w, align='edge')

结果:

您还可以制作一个直方图,其中每个 bin 的宽度为 1,但这是一个更有限的解决方案。

编辑:正如其他答案中所指出的,这基本上相当于将正确的weights 参数提供给plt.hist。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    • 2015-05-26
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 2016-02-12
    相关资源
    最近更新 更多