Python數據可視化第 7 講:matplotlib繪製直方圖函數hist

1. hist 函數介紹

hist 函數用於繪製直方圖,直方圖本質上是一種統計圖。hist 函數繪圖數據由參數 x 提供,參數 x 提供多個數據,作爲具有潛在不同長度的數據集列表([x0,x1,…]),也可以作爲每個列都是數據集的二維數組。函數的調用格式如下:

hist(x, bins, **kwargs)
hist(x)

主要參數說明:

  • x:數組或序列輸入值,必須參數,它接受一個數組或一系列不需要具有相同長度的數組。
  • bins:整數或序列或字符串,可選參數。如果 bins 是整數,則定義範圍內等寬箱子(直方圖塊)的數量;如果 bins 是一個序列,它定義箱子邊緣,包括第一個箱子的左邊緣和最後一個箱子的右邊緣;在這種情況下,箱子的間距可能不相等。除了最後一個(最右邊的)箱子是半開的。舉個例子,如果 bins 是:[1, 2, 3, 4],那麼第一個箱子是 [1,2(包括1,但不包括2),第二個箱子是[2,3);然而,最後一個箱子是[3,4],其中包括4。

2. hist 函數繪圖示例

2.1 繪製一個簡單的直方圖

繪製一個簡單的直方圖。代碼如下,數據集 x 提供繪圖數據,bins=6 表示繪製的直方圖塊爲 6 個,也就是將 x 提供的數據劃分爲 6 個區間進行分別統計,即分別統計數據集 x 中的數據落在區間 [1,1.5)、[1.5,2.0)、[2.0,2.5)、…、[3.5,4] 這 6 個區間的數量。直方圖的高度就是落在對應區間的數據個數。

import matplotlib.pyplot as plt

# step1:準備畫圖的數據
x = [1, 2, 3, 4, 1, 2, 3, 4, 3, 2, 4, 2, 1, 4, 3, 2, 2, 2, 2, 3, 3, 2, 3, 4, 2, 2, 2]
# step2:手動創建一個figure對象,相當於一個空白的畫布
figure = plt.figure()
# step3:在畫布上添加1個子塊,標定繪圖位置
axes1 = plt.subplot(1, 1, 1)
# step4:繪製直方圖
axes1.hist(x, bins=6)
axes1.set_title('a simple histogram')
# step5:展示
plt.show()

上面代碼的運行結果:很明顯,落在區間[2.0,2.5) 的數據是最多的。

2.2 通過numpy生成數據繪製一個直方圖

通過 numpy 生成數據繪製一個直方圖,代碼如下:

import matplotlib.pyplot as plt
import numpy as np

# step1:準備畫圖的數據
N_points = 100000
n_bins = 20
x = np.random.randn(N_points)
# step2:手動創建一個figure對象,相當於一個空白的畫布
figure = plt.figure()
plt.rcParams['axes.unicode_minus'] = False  # 解決保存圖像是負號'-'顯示爲方塊的問題
# step3:在畫布上添加1個子塊,標定繪圖位置
axes1 = plt.subplot(1, 1, 1)
# step4:繪製直方圖
axes1.hist(x, bins=n_bins)
axes1.set_title('a simple histogram')

# step5:展示
plt.show()

上面代碼的運行結果:

2.3 繪製具有多個數據集的直方圖

繪製具有多個數據集的直方圖,並設置基本屬性,代碼示例如下:

import matplotlib.pyplot as plt
import numpy as np

# step1:準備畫圖的數據
np.random.seed(19680801)
n_bins = 10
x = np.random.randn(1000, 3)
colors = ['red', 'tan', 'lime']

# step2:手動創建一個figure對象,相當於一個空白的畫布
figure = plt.figure()
plt.rcParams['axes.unicode_minus'] = False  # 解決保存圖像是負號'-'顯示爲方塊的問題
# step3:在畫布上添加1個子塊,標定繪圖位置
axes1 = plt.subplot(1, 1, 1)
# step4:繪製直方圖
axes1.hist(x, n_bins, density=True, histtype='bar', color=colors, label=colors)
axes1.set_title('a simple histogram')
axes1.legend()

# step5:展示
plt.show()

上面代碼的運行結果:

2.4 直方圖與擬合曲線

在繪製直方圖的基礎上,繪製一條擬合曲線,代碼如下:

import matplotlib.pyplot as plt
import numpy as np

# step1:準備畫圖的數據
mu = 100  # mean of distribution
sigma = 15  # standard deviation of distribution
x = mu + sigma * np.random.randn(437)
num_bins = 50

# step2:手動創建一個figure對象,相當於一個空白的畫布
figure = plt.figure()
plt.rcParams['axes.unicode_minus'] = False  # 解決保存圖像是負號'-'顯示爲方塊的問題
# step3:在畫布上添加1個子塊,標定繪圖位置
axes1 = plt.subplot(1, 1, 1)
# step4:繪製直方圖
n, bins, patches = axes1.hist(x, num_bins, density=1)
# step5:繪製一條擬合曲線
y = ((1 / (np.sqrt(2 * np.pi) * sigma)) *
     np.exp(-0.5 * (1 / sigma * (bins - mu)) ** 2))
axes1.plot(bins, y, '--')
# step6:設置基本元素
axes1.set_xlabel('Smarts')
axes1.set_ylabel('Probability density')
axes1.set_title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')

# step7:展示
plt.show()

上面代碼的運行結果:

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