Python繪制直方圖的示例代碼
初步
對于大量樣本來說,如果想快速獲知其分布特征,最方便的可視化方案就是直方圖,即統(tǒng)計落入不同區(qū)間中的樣本個數(shù)。
以正態(tài)分布為例
import numpy as np
import matplotlib.pyplot as plt
xs = np.random.normal(0, 1, size=(5000))
fig = plt.figure()
for i,b in enumerate([10, 50, 100, 200],1):
ax = fig.add_subplot(2,2,i)
plt.hist(xs, bins=b)
plt.show()其中bins參數(shù)用于調(diào)控區(qū)間個數(shù),出圖結(jié)果如下

參數(shù)
直方圖函數(shù)的定義如下
hist(x, bins=None, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, *, data=None, **kwargs)
除了x和bins之外,其他參數(shù)含義為
- range 繪圖區(qū)間,默認(rèn)將樣本所有范圍納入其中
- density 為
True時,縱坐標(biāo)單位是占比 - weights 與
x個數(shù)相同,表示每個值所占權(quán)重 - cumulative 為
True時,將采取累加模式 - bottom y軸起點,有了這個,可以對直方圖進行堆疊
- histtype 繪圖類型
- align 對其方式,可選left, mid, right三種,代表左中右
- oritentation 繪制方向,可選vertical和horizontal兩種
- rwitdth 數(shù)據(jù)條寬度
- log 為
True時,開啟對數(shù)坐標(biāo) - color, label 顏色,標(biāo)簽
- stacked
繪圖類型
histtype共有4個選項,分別是bar, barstacked, step以及stepfilled,其中barstacked表示堆疊,下面對另外三種參數(shù)進行演示
types = ['bar', 'step', 'stepfilled']
fig = plt.figure()
for i,t in enumerate(types,1):
ax = fig.add_subplot(1,3,i)
plt.hist(xs, bins=50, histtype=t, rwidth=0.5)
plt.show()效果如下

堆疊直方圖,就是把多個直方圖疊在一起
bins = [10, 30, 100]
ws = [1, 0.7, 0.5]
for b,w in zip(bins, ws):
print(b,w)
plt.hist(xs, bins=b, density=True,
histtype='barstacked', rwidth = w, alpha=w)
plt.show()效果如下

多組數(shù)據(jù)直方圖對比
直方圖中設(shè)置了rwidth選項,這意味著可以通過合理安排數(shù)據(jù)條寬度,以實現(xiàn)多組數(shù)據(jù)直方圖在一個圖像中更加
N = 10000
labels = ["norm", "power", "poisson"]
data = np.array([
np.random.normal(0, 1, size=N)**2,
np.random.power(5, size=N),
np.random.uniform(0, 1, size=N)
]).T
plt.hist(data, 50, density=True, range=(0,1), label=labels)
plt.legend()
plt.show()其中,data為3組統(tǒng)計數(shù)據(jù),hist函數(shù)會自行規(guī)劃畫布,效果如下

到此這篇關(guān)于Python繪制直方圖的示例代碼的文章就介紹到這了,更多相關(guān)Python繪制直方圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python 出現(xiàn)SyntaxError: non-keyword arg after keyword arg錯誤解決辦
這篇文章主要介紹了python 出現(xiàn)SyntaxError: non-keyword arg after keyword arg錯誤解決辦法的相關(guān)資料,需要的朋友可以參考下2017-02-02
Python version 2.7 required, which was not found in the regi
這篇文章主要介紹了安裝PIL庫時提示錯誤Python version 2.7 required, which was not found in the registry問題的解決方法,需要的朋友可以參考下2014-08-08

