WeHelp
Matplotlib 是 Python 用來做資料視覺化的熱門工具,能建立各式各樣的資料圖表。
  1. 簡介、安裝、快速開始
  2. 繪製圓餅圖
  3. 繪製折線圖
  4. 繪製散佈圖
  5. 繪製長條圖
  6. 繪製直方圖
  7. 繪製 K 線圖
  8. 中文字型問題處理
繪製直方圖
# 使用 Matplotlib 繪製直方圖(Histogram Chart) 直方圖用來觀察數值資料的分布情形。它會將資料切分成數個區間(bins),並統計每個區間內包含多少筆資料。 Matplotlib 中主要使用: ```python plt.hist(data) ``` 或物件導向寫法: ```python ax.hist(data) ``` --- ## 常用設定 ```python plt.hist( data, bins=10, range=None, density=False, cumulative=False, color="skyblue", edgecolor="black", alpha=0.7, histtype="bar" ) ``` 常見參數說明: | 參數 | 說明 | |---|---| | `data` | 要繪製的數值資料 | | `bins` | 區間數量,也可以傳入區間邊界列表 | | `range` | 指定資料顯示範圍,例如 `(0, 100)` | | `density=True` | 將縱軸改為機率密度,而不是資料筆數 | | `cumulative=True` | 繪製累積直方圖 | | `color` | 柱子的顏色 | | `edgecolor` | 柱子邊框顏色 | | `alpha` | 透明度,範圍通常是 `0` 到 `1` | | `histtype` | 圖形類型,例如 `"bar"`、`"step"`、`"stepfilled"` | | `label` | 圖例名稱 | 其他常用設定: ```python plt.title("Histogram") plt.xlabel("Value") plt.ylabel("Frequency") plt.grid(axis="y", alpha=0.3) plt.legend() plt.xlim(0, 100) plt.ylim(0, 20) plt.show() ``` --- # 範例一:繪製考試成績直方圖 以下範例使用一組考試成績,將成績分成 10 個區間。 ```python import matplotlib.pyplot as plt # 考試成績 scores = [ 55, 62, 68, 70, 72, 75, 78, 80, 81, 83, 85, 86, 88, 90, 91, 92, 95, 96, 98, 100 ] plt.figure(figsize=(8, 5)) plt.hist( scores, bins=10, range=(0, 100), color="skyblue", edgecolor="black", alpha=0.8 ) plt.title("Distribution of Exam Scores") plt.xlabel("Score") plt.ylabel("Number of Students") # 設定刻度 plt.xticks(range(0, 101, 10)) # 只顯示水平格線 plt.grid(axis="y", linestyle="--", alpha=0.4) plt.tight_layout() plt.show() ``` ## 說明 ```python bins=10 ``` 代表將資料分成 10 個區間。 ```python range=(0, 100) ``` 表示只觀察 0 到 100 的成績範圍。 ```python edgecolor="black" ``` 設定每個柱子的邊框顏色,能讓區間更加清楚。 --- # 範例二:比較兩組資料的分布 可以在同一張圖中繪製兩組資料,例如比較男生與女生的成績分布。這時通常會使用透明度 `alpha`,避免圖形互相遮住。 ```python import matplotlib.pyplot as plt import numpy as np # 固定亂數結果,方便重複執行時得到相同資料 np.random.seed(42) # 產生兩組模擬成績 group_a = np.random.normal(loc=75, scale=8, size=200) group_b = np.random.normal(loc=82, scale=6, size=200) # 將成績限制在 0 到 100 group_a = np.clip(group_a, 0, 100) group_b = np.clip(group_b, 0, 100) plt.figure(figsize=(8, 5)) plt.hist( group_a, bins=12, range=(0, 100), alpha=0.55, color="steelblue", edgecolor="black", label="Group A" ) plt.hist( group_b, bins=12, range=(0, 100), alpha=0.55, color="orange", edgecolor="black", label="Group B" ) plt.title("Comparison of Two Score Distributions") plt.xlabel("Score") plt.ylabel("Number of Students") plt.xticks(range(0, 101, 10)) plt.grid(axis="y", linestyle="--", alpha=0.4) plt.legend() plt.tight_layout() plt.show() ``` ## 說明 兩次呼叫 `plt.hist()` 會將兩組資料繪製在同一張圖上: ```python alpha=0.55 ``` 設定半透明效果,使重疊的區域仍然可以看見。 ```python label="Group A" ``` 指定圖例文字,再透過: ```python plt.legend() ``` 顯示圖例。 --- # 其他常見用法 ## 1. 使用機率密度顯示 如果想比較不同樣本數的資料分布,可以使用: ```python plt.hist(data, bins=20, density=True) ``` 此時縱軸不是資料筆數,而是機率密度。 --- ## 2. 繪製階梯式直方圖 ```python plt.hist( data, bins=20, histtype="step", color="green", linewidth=2 ) ``` `histtype="step"` 適合用來比較多組資料,視覺上較不容易互相遮蔽。 --- ## 3. 自訂區間邊界 `bins` 不一定只能設定數字,也可以直接指定每個區間的邊界: ```python import matplotlib.pyplot as plt data = [12, 18, 25, 31, 36, 42, 49, 55, 63, 71, 88] bins = [0, 20, 40, 60, 80, 100] plt.hist(data, bins=bins, edgecolor="black") plt.xlabel("Value") plt.ylabel("Frequency") plt.title("Custom Bins") plt.show() ``` 這會建立以下區間: - 0–20 - 20–40 - 40–60 - 60–80 - 80–100 `bins` 數量越多,圖形越細;數量越少,圖形越平滑,但可能遺失資料分布的細節。
相關學習地圖、教學課程
Python 資料工程
從 0 開始,成為資料工程師的學習路徑。