文章目錄
[ Matplotlib version: 3.2.1 ]
七、頻次直方圖、數據區間劃分和分佈密度
(一)簡易頻次直方圖
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
date = np.random.randn(1000)
plt.hist(data)
自定義頻次直方圖
plt.hist(data, bins=30, density=True, alpha=0.5, histtype='stepfilled', color='steelblue', edgecolor='none')
同坐標軸的多個頻次直方圖
用頻次直方圖對不同分佈特徵的樣本進行對比時,將histtype='stepfilled'
與透明性設置參數alpha
搭配使用的效果非常好
x1 = np.random.normal(0, 0.8, 1000)
x2 = np.random.normal(-2, 1, 1000)
x3 = np.random.normal(3, 2, 1000)
kwargs = dict(histtype='stepfilled', alpha=0.3, density=True, bins=40)
plt.hist(x1, **kwargs)
plt.hist(x2, **kwargs)
plt.hist(x3, **kwargs)
如果只需要簡單計算頻次直方圖(計算每段區間的樣本數),而不像畫圖顯示它們,可以直接用np.histogram()
counts, bin_edges = np.histogram(data, bins=5)
counts
# array([ 36, 255, 445, 230, 34])
(二)二維頻次直方圖與數據區間劃分
如同將一維數組分爲區間創建一維頻次直方圖,也可以將二維數組按照二維區間進行切分,創建二維頻次直方圖
首先,用一個多元高斯分佈(multivariate Gaussian distribution)生成x軸與y軸的樣本數據
mean = [0, 0]
cov = [[1, 1], [1, 2]]
x, y = np.random.multivariate_normal(mean, cov, 10000).T
1. plt.hist2d:二維頻次直方圖
畫二維頻次直方圖最簡單的方法就是使用Matplotlib的plt.hist2d
函數
plt.hist2d(x, y, bins=30, cmap='Blues')
cb = plt.colorbar()
cb.set_label('counts in bin')
plt.hist2d
中,與np.histogram
類似函數是np.histogram2d
counts, xedges, yedges = np.histogram2d(x, y, bins=30)
2. plt.hexbin:六邊形區間劃分
二維頻次直方圖是由與座標軸正交的方塊分割而成的,還有一種常用的方式是用正六邊形分割。
Matplotlib提供plt.hexbin
,可以將二維數據集分割成蜂窩狀
plt.hexbin(x, y, gridsize=30, cmap='Blues')
cb = plt.colorbar(label='count in bin')
3. 核密度估計
還有一種評估多維數據分佈密度的常用方法是核密度估計(kernel density estimation, KDE)
簡單演示如何用KDE方法“抹掉”空間中離散的數據點,從而擬合出一個平滑的函數。(scipy.stats
中有一個快速實現KDE方法)
from scipy.stats import gaussian_kde
# 擬合數組維度[Ndim, Nsamples]
data = np.vstack([x, y])
kde = gaussian_kde(data)
# 用一對規則的網格數據進行擬合
xgrid = np.linspace(-3.5, 3.5, 40)
ygrid = np.linspace(-6, 6, 40)
Xgrid, Ygrid = np.meshgrid(xgrid, ygrid)
Z = kde.evaluate(np.vstack([Xgrid.ravel(), Ygrid.ravel()]))
# 畫出結果圖
plt.imshow(Z.reshape(Xgrid.shape), origin='lower', aspect='auto',
extent=[-3.5, 3.5, -6, 6], cmap='Blues')
cb = plt.colorbar()
cb.set_label('density')
- KDE方法通過不同的平滑帶寬長度(smoothing length)在擬合函數的準確性與平滑性之間作出權衡。
- 想找到恰當的平滑帶寬長度是件很難的事,
gaussian_kde
通過一種經驗方法試圖找到輸入數據平滑長度的近似最優解。 - 在Scipy的生態系統中還有其他的KDE方法實現,每種版本都有各自優缺點,如
sklearn.neighbors.KernelDensity
,statsmodels.nonparametric.kernel_density.KDEMultivariate
- 用Matplotlib做KDE的可視化圖的過程比較繁瑣,Seaborn提供了更加簡潔的API來創建基於KDE的可視化圖
Matplotlib 相關閱讀:
[Python3] Matplotlib —— (一) 入門基礎
[Python3] Matplotlib —— (二) 簡易線形圖
[Python3] Matplotlib —— (三) 簡易散點圖
[Python3] Matplotlib —— (四) 可視化異常處理
[Python3] Matplotlib —— (五) 密度圖與等高線圖
總結自《Python數據科學手冊》