【问题标题】:Extra bar in the first bin of a pyplot histogrampyplot 直方图的第一个 bin 中的额外条
【发布时间】:2015-04-22 07:53:34
【问题描述】:

绘制直方图时,会有一个不应存在的额外条形图。尽管hist 输出报告的频率为零,但第一个 bin 中的条形高度不为零。

这是一个最小的例子:

import numpy as np
import matplotlib.pyplot as plt
import random

t=np.array([random.random() for _ in range(10000)])
bins=np.linspace(-0.1, 1.1, 101)
plt.hist(t, bins)
plt.show()

在第一个 bin 中生成了一个条形,可以在此图的左边缘和直方图的主要部分之间看到它(在缩略图上很难看到,放大图像):

打印出print("%2.32f" %plt.hist(t1, bins)[0][1]) 会给出精确为零的值。

【问题讨论】:

  • 有趣!我看到一个非常微妙的“条”,它似乎只由条边组成,没有高度,也没有填充。如果我使用plt.bar 绘制相同的直方图 (counts, edges = np.histogram(t, bins); plt.bar(edges[:-1], counts, np.diff(edges))),则它不存在。你能确认一下吗?
  • @ali_m 很好的观察,它实际上只是一条线,即条形图没有填充或高度。 plt.bar 似乎没有产生它,所以谢谢你的建议。

标签: python numpy matplotlib histogram


【解决方案1】:

这是 matplotlib 中的一个小错误,最初是在 this commit 中引入的。基本上,所有 bin 边缘的顶点都设置为“捕捉”到最近的像素中心,但第一个 bin 除外。这样做是为了修复另一个错误,即捕捉第一个 bin 边缘会阻止直方图 bin 与相应的线图正确对齐。

There is an open issue relating to this on the matplotlib GitHub page,所以希望尽快解决。

同时,您可以使用plt.bar(正如我在 cmets 中提到的),或者为第一个直方图补丁手动设置捕捉:

counts, edges, patches = plt.histogram(t, bins)
patches[0].set_snap(True)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-07
    • 2015-03-22
    • 1970-01-01
    • 2015-07-26
    • 2016-06-23
    • 1970-01-01
    • 2017-12-12
    • 2012-06-08
    相关资源
    最近更新 更多