pyplot 直方图的第一个 bin 中的额外条

Extra bar in the first bin of a pyplot histogram

绘制直方图时,有一个不应该出现的额外条形图。第一个 bin 中的条具有非零高度,即使 hist 输出报告的频率为零。

这是一个最小的例子:

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]) 给出的值恰好为零。

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

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

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

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