如何使用 Python 中的 Matplotlib 建立直方圖?
Matplotlib 是一個流行的 Python 包,用於資料視覺化。
資料視覺化是一個關鍵步驟,因為它有助於理解資料中發生的情況,而無需實際檢視數字並執行復雜的計算。
它有助於有效地將定量見解傳達給受眾。
Matplotlib 用於使用資料建立二維圖。它帶有一個面向物件的 API,有助於將繪圖嵌入 Python 應用程式中。Matplotlib 可以與 IPython shell、Jupyter notebook、Spyder IDE 等一起使用。
它是用 Python 編寫的。它是使用 Numpy 建立的,Numpy 是 Python 中的數值 Python 包。
可以使用以下命令在 Windows 上安裝 Python:
pip install matplotlib
Matplotlib 的依賴項為:
Python ( greater than or equal to version 3.4) NumPy Setuptools Pyparsing Libpng Pytz Free type Six Cycler Dateutil
讓我們瞭解一下如何使用 Matplotlib 在繪圖中繪製直方圖:
示例
import matplotlib import numpy as np import matplotlib.pyplot as plt np.random.seed(19875871) meanVal = 125 stdDevVal = 35 x = meanVal + stdDevVal * np.random.randn(764) num_bins = 36 fig, ax = plt.subplots() n, bins, patches = ax.hist(x, num_bins, density=True) y = ((1 / (np.sqrt(2 * np.pi) * stdDevVal)) * np.exp(−0.5 * (1 / stdDevVal * (bins - meanVal))**2)) ax.plot(bins, y, '−−') ax.set_xlabel('X−axis') ax.set_ylabel('y−axis') ax.set_title('A simple histogram') fig.tight_layout() plt.show()
輸出
解釋
匯入所需的包並定義其別名以方便使用。
使用“random”庫的“seed”函式建立資料。
定義“均值”和“標準差”值。
定義箱數,即直方圖中需要顯示的矩形塊的數量。
使用“figure”函式建立一個空圖形。
使用“hist”函式建立直方圖。
使用“plot”函式繪製資料。
使用 set_xlabel、set_ylabel 和 set_title 函式為“X”軸、“Y”軸和標題提供標籤。
還使用虛線顯示分佈 - 這是一條鐘形曲線。
使用“show”函式在控制檯上顯示。
廣告