[英]Choice of bins for histograms with relatively few datapoints
考虑在matplotlib中具有多个直方图的图,如下所示:
#! /usr/bin/env python3
import matplotlib.pyplot as plt
import random
# Use the same seed for reproducibility.
random.seed(10586)
data1 = [random.gauss(1e-4, 3e-2) for _ in range(10**3)] + [0.3]
data2 = [random.gauss(1e-2, 3e-3) for _ in range(10**3)] + [0.4]
data3 = [0.2]
if __name__ == '__main__':
plt.xlim(xmin=0, xmax=0.8)
plt.yscale('log')
n1, bins1, patches1 = plt.hist(data1, bins='auto', alpha=0.6)
n2, bins2, patches2 = plt.hist(data2, bins='auto', alpha=0.6)
n3, bins3, patches3 = plt.hist(data3, bins='auto', alpha=0.6)
bin_options = ['auto', 'fd', 'doane', 'scott', 'rice', 'sturges', 'sqrt']
plt.show()
但是,第三个数据集只有一个数据点,因此,当我们使用plt.hist(data3, bins='auto')
我们会在x范围内看到一条长条,并且不再看到其值为0.2:
(只有一个数据点最明显,但是例如两个或三个也是一个问题。)
避免这种情况的一种方法是仅重复使用另一个数据集的bin。 例如,对于plt.hist(data3, bins=bins1)
我们可以看到data3
就好了:
但是,如果我们通过bins=bins2
使用其他数据集,则bin太窄,我们根本看不到data3
:
我们如何确保直方图的点相对较少可见,但仍在x轴上看到其值?
为了确保您看到条形图,即使它太窄而无法包含一个像素,您也可以为其设置边缘颜色,
import matplotlib.pyplot as plt
import random
random.seed(10586)
data2 = [random.gauss(1e-2, 3e-3) for _ in range(10**3)] + [0.4]
plt.xlim(0, 0.8)
plt.yscale('log')
n2, bins2, patches2 = plt.hist(data2, bins='auto', alpha=0.6, edgecolor="C0")
plt.show()
或使用histtype="stepfilled"
创建多边形,因为单个条形图无论如何也无法与那么多图元区分开,
n2, bins2, patches2 = plt.hist(data2, bins='auto', alpha=0.6, histtype="stepfilled")
后者还具有服从Alpha的优势,否则由于条形重叠而无法看到。 同样,绘制单个形状应该更快,而不是大约1000条。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.