python:繪製直方圖(Histogram)

簡介

本文主要總結如何繪製直方圖,以及常用的使用場景。

什麼是直方圖:一個隨機變量在各個取值區間有個概率分佈,將其繪製出來:x軸爲等間隔的取值區間(bins),y軸爲該區間的頻數(可歸一化),即直方圖。

接口

Signature:
plt.hist(
    x,
    bins=None,
    range=None,
    density=None,
    weights=None,
    cumulative=False,
    bottom=None,
    histtype='bar',
    align='mid',
    orientation='vertical',
    rwidth=None,
    log=False,
    color=None,
    label=None,
    stacked=False,
    normed=None,
    *,
    data=None,
    **kwargs,
)
Docstring:
Plot a histogram.

Compute and draw the histogram of *x*. The return value is a
tuple (*n*, *bins*, *patches*) or ([*n0*, *n1*, ...], *bins*,
[*patches0*, *patches1*,...]) if the input contains multiple
data.

實例1:正態分佈的直方圖

實例
生成一個正態分佈數據x,然後繪製其直方圖。
代碼

mu,sigma = 0,1
x = np.random.normal(mu,sigma,size=5000)
n, bins,patches = plt.hist(x,bins=20)
print('n:',n)
print('bins:',bins)
print('patches:',patches)

分析
輸入參數:

  • x:即隨機變量的取值數據
  • bins:表示將x等間隔分成多少個區間。比如這裏分成了20個區間,具體說:它是將[min(x),max(x)]這個範圍等間隔分成20個區間(bin),即有21個區間端點。

返回參數:

  • n:各區間(bin)的頻數,即20個柱子的高度,
  • bins:21個區間端點。查看數值可以看到第一個端點爲min(x),最後一個端點爲max(x)。
  • patches:表示20個柱子

結果

n: [  2.   1.  22.  36.  81. 161. 329. 448. 580. 703. 745. 590. 507. 354.
 217. 115.  73.  25.  10.   1.]
bins: [-3.66700533 -3.30660994 -2.94621455 -2.58581916 -2.22542377 -1.86502838
 -1.50463298 -1.14423759 -0.7838422  -0.42344681 -0.06305142  0.29734397
  0.65773937  1.01813476  1.37853015  1.73892554  2.09932093  2.45971632
  2.82011172  3.18050711  3.5409025 ]
patches: <a list of 20 Patch objects>

在這裏插入圖片描述

拓展
使用其他輸入參數,可以改進直方圖。常用的有:

1、指定分隔範圍:range
使用場景:1.想讓區間數據更清晰;2.扔掉一些區間外的‘壞點’

n, bins,patches = plt.hist(x,bins=20,range=(-3,3))
print(‘bins:’,bins)

結果:

bins: [-3.  -2.7 -2.4 -2.1 -1.8 -1.5 -1.2 -0.9 -0.6 -0.3  0.   0.3  0.6  0.9
  1.2  1.5  1.8  2.1  2.4  2.7  3. ]

在這裏插入圖片描述

2、將頻數歸一化爲概率密度:density
縱軸默認爲頻數,可歸一化爲概率密度。即歸一化後,所有柱子的面積之和爲1,即某區間的概率密度=頻數/總數/區間長度,可理解爲該區間的平均概率密度(或該區間的中值點的概率密度)
預期結果:歸一化後的概率密度與標準的正態分佈函數(概率密度函數)是吻合的。

_ ,ax = plt.subplots()
n, bins,patches = ax.hist(x,bins=20,range=(-3,3),density=True)
# 驗證正態分佈
y1 = scipy.stats.norm.pdf(bins, loc=mu, scale=sigma)
#y2 = 1/(sigma * np.sqrt(2 * np.pi)) * np.exp( - (bins - mu)**2 / (2 * sigma**2))
ax.plot(bins,y1,'r--')

結果:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章