[英]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.