【问题标题】:Strange behavior in matplotlib (multiple) histogramsmatplotlib(多个)直方图中的奇怪行为
【发布时间】:2017-01-14 22:01:13
【问题描述】:

我尝试使用标准方法在同一画布上绘制两个直方图:

    plt.figure(figsize=(8,6))
    plt.hist(samp_1_I, label=['Female'], alpha=0.5)
    plt.hist(samp_0_I, label=['Male'], alpha=0.5)
    plt.tick_params(axis='both', which='major', labelsize=18)
    plt.legend(fontsize=18)
    plt.show()

结果是: 如果您注意到,直方图“条形”未对齐到末端(最右侧)。如何解决?有人见过这个吗?

水平轴是有理数 [0,1],默认情况下它被分箱到 0.1 的 10 个 bin 中。我不明白为什么两组的条形不像一开始那样对齐。

【问题讨论】:

  • 数据的实际范围是多少?看起来你的蓝色条的最高值可能是 0.98 或其他值,而不是 1。尝试明确设置垃圾箱。
  • @BrenBam,有道理!谢谢!
  • 一个快速的问题:如果我标准化我的直方图,垂直轴的含义是什么?归一化频率?

标签: python matplotlib histogram


【解决方案1】:

如果您想要 10 个 binwidth 为 0.1 的 bin,您需要在对 plt.hist 的调用中提供这些 bin。

import matplotlib.pyplot as plt
import numpy as np

samp_1_I = np.random.rand(14)
samp_0_I = np.random.rand(17)

bins= np.arange(11)/10.

plt.figure(figsize=(8,6))
plt.hist(samp_1_I, bins=bins, label=['Female'], alpha=0.5)
plt.hist(samp_0_I, bins=bins, label=['Male'], alpha=0.5)
plt.tick_params(axis='both', which='major', labelsize=18)
plt.legend(fontsize=18)
plt.show()


回答 cmets 的问题: 使用normed=True,您将获得归一化频率,即每个bin 宽度乘以频率的总和为1
sample = np.random.rand(14)
bins= np.arange(11)/10.
hist, _bins = np.histogram(sample, bins=bins, normed = True)
print hist
print np.sum ( hist * np.diff(bins) ) # This prints 1.0

即使 bin 宽度不同,这也成立。

【讨论】:

  • 没错!我只是假设默认分箱是您指定的分箱。谢谢大家!
  • 一个快速的问题:如果我标准化我的直方图,垂直轴的含义是什么?归一化频率?
  • @ArnoldKlein 查看关于您的问题的已编辑答案。
猜你喜欢
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-22
  • 1970-01-01
  • 2014-03-17
  • 1970-01-01
相关资源
最近更新 更多