箱的选择与相对较少的数据点直方图

问题描述 投票:0回答:1

考虑与多个histograms in 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:

stretched out

(这是只有一个数据点最明显,但它是一个问题,例如有两个或三个也。)

一种方法来避免这种情况,只是重新使用另一个数据集的垃圾箱。例如,对于plt.hist(data3, bins=bins1),我们可以看到data3就好了:

what we want

但是,如果我们用其他的数据通过bins=bins2设定,垃圾箱太窄,我们不能看到data3都:

all gone

我们如何才能确保相对较少的点直方图是可见的,但仍然可以看到在x轴的价值?

python matplotlib histogram binning
1个回答
1
投票

为了确保你看到了吧,哪怕是太窄,包括像素,你可以给它一个edgecolor,

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()

enter image description here

或者使用histtype="stepfilled"创建一个多边形,因为个别酒吧的不区分与许多垃圾箱反正,

n2, bins2, patches2 = plt.hist(data2, bins='auto', alpha=0.6, histtype="stepfilled")

enter image description here

后者也有服从α,其否则没有看到由于杆的重叠的优点。此外,它应该是一个更快的绘图一个单一的形状,而不是一些1000条。

© www.soinside.com 2019 - 2024. All rights reserved.