NumPy - 使用 Matplotlib 繪製直方圖



NumPy 有一個 **numpy.histogram()** 函式,它以圖形方式表示資料的頻率分佈。矩形具有相同的水平大小,對應於稱為 **bin** 的類間隔和對應於頻率的 **可變高度**。

numpy.histogram()

numpy.histogram() 函式將輸入陣列和 bin 作為兩個引數。bin 陣列中的連續元素充當每個 bin 的邊界。

import numpy as np 
   
a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27]) 
np.histogram(a,bins = [0,20,40,60,80,100]) 
hist,bins = np.histogram(a,bins = [0,20,40,60,80,100]) 
print hist 
print bins 

它將產生以下輸出 -

[3 4 5 2 1]
[0 20 40 60 80 100]

plt()

Matplotlib 可以將直方圖的這種數值表示轉換為圖形。pyplot 子模組的 **plt() 函式** 將包含資料的陣列和 bin 陣列作為引數,並將其轉換為直方圖。

from matplotlib import pyplot as plt 
import numpy as np  
   
a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27]) 
plt.hist(a, bins = [0,20,40,60,80,100]) 
plt.title("histogram") 
plt.show()

它應該產生以下輸出 -

Histogram Plot
廣告