本文 AI 產出,尚未審核

Matplotlib / Seaborn 基礎


簡介

在資料科學與機器學習的工作流程中,視覺化是不可或缺的一環。透過圖表,我們能快速發現資料的分布、趨勢或異常值,進而做出更有依據的決策。Python 生態系最常使用的兩個視覺化套件是 MatplotlibSeaborn;前者是底層繪圖引擎,提供彈性極高的控制介面;後者則是基於 Matplotlib 的高階 API,專注於統計圖形與美觀的預設樣式。

本篇文章以 初學者到中級開發者 為目標,從概念說明、實作範例到常見陷阱與最佳實踐,完整呈現如何在 Python 中使用 Matplotlib 與 Seaborn 進行資料處理與視覺化。閱讀完畢,你將能夠:

  1. 快速產生常見圖表(折線圖、散佈圖、長條圖、箱形圖…)。
  2. 自訂圖表外觀(字型、顏色、圖例、座標軸等)。
  3. 結合 Seaborn 的統計圖形,提升圖表的資訊密度與美感。

核心概念

1️⃣ Matplotlib 基本結構

Matplotlib 的核心物件是 Figure(整張圖)與 Axes(子圖/座標系)。最常見的使用方式是透過 pyplot(簡稱 plt)的函式式 API,讓繪圖流程像寫腳本一樣直觀。

import matplotlib.pyplot as plt

# 建立 Figure 與 Axes(預設 1x1)
fig, ax = plt.subplots(figsize=(8, 5))

# 繪製簡單折線圖
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
ax.plot(x, y, marker='o', color='steelblue', linewidth=2, label='Prime')
ax.set_title('簡單折線圖')
ax.set_xlabel('X 軸')
ax.set_ylabel('Y 軸')
ax.legend()
plt.show()

重點

  • plt.subplots() 同時回傳 FigureAxes,方便後續調整。
  • ax.plot() 的參數(markercolorlinewidth)可以即時改變線條樣式。

2️⃣ 常用圖形:Line、Scatter、Bar

圖形 典型用途 主要函式
折線圖 (Line) 時間序列、趨勢觀察 ax.plot()
散佈圖 (Scatter) 兩變數關係、群聚分析 ax.scatter()
長條圖 (Bar) 類別比較、頻率分布 ax.bar()

2.1 折線圖 + 多條線

import numpy as np

t = np.arange(0, 2*np.pi, 0.1)
sin = np.sin(t)
cos = np.cos(t)

fig, ax = plt.subplots()
ax.plot(t, sin, label='sin(t)', color='tab:red')
ax.plot(t, cos, label='cos(t)', color='tab:green')
ax.set_title('Sin & Cos 曲線')
ax.set_xlabel('角度 (rad)')
ax.set_ylabel('幅度')
ax.grid(True, linestyle='--', alpha=0.5)
ax.legend()
plt.show()

2.2 散佈圖 + 顏色映射

np.random.seed(0)
x = np.random.randn(200)
y = np.random.randn(200)
size = np.random.rand(200) * 300   # 點的大小
color = np.sqrt(x**2 + y**2)       # 距離原點的距離作為顏色依據

fig, ax = plt.subplots()
scatter = ax.scatter(x, y, s=size, c=color, cmap='viridis', alpha=0.7)
fig.colorbar(scatter, ax=ax, label='距離原點')
ax.set_title('散佈圖 + 顏色映射')
ax.set_xlabel('X')
ax.set_ylabel('Y')
plt.show()

2.3 長條圖 + 標註值

categories = ['A', 'B', 'C', 'D']
values = [23, 45, 56, 12]

fig, ax = plt.subplots()
bars = ax.bar(categories, values, color='skyblue')
ax.set_title('類別長條圖')
ax.set_ylabel('數量')

# 為每根長條加上數值標註
for bar in bars:
    height = bar.get_height()
    ax.annotate(f'{height}',
                xy=(bar.get_x() + bar.get_width() / 2, height),
                xytext=(0, 3),  # 垂直偏移 3pt
                textcoords="offset points",
                ha='center', va='bottom')
plt.show()

3️⃣ Seaborn 基本概念

Seaborn 以 資料框 (DataFrame) 為輸入,內建許多統計圖形(如箱形圖、分布圖、熱圖),同時提供美觀的預設樣式。安裝方式:

pip install seaborn

3.1 載入與設定樣式

import seaborn as sns
import pandas as pd

# 設定全域樣式
sns.set_theme(style='whitegrid', palette='muted')

3.2 常見圖形:箱形圖 (Boxplot)

# 產生示範資料
df = pd.DataFrame({
    'class': ['A']*30 + ['B']*30,
    'score': np.concatenate([np.random.normal(70, 5, 30),
                             np.random.normal(78, 7, 30)])
})

fig, ax = plt.subplots()
sns.boxplot(x='class', y='score', data=df, ax=ax)
ax.set_title('不同班級的分數箱形圖')
plt.show()

3.3 分布圖 (Histogram + KDE)

fig, ax = plt.subplots()
sns.histplot(df['score'], kde=True, bins=15, color='steelblue', ax=ax)
ax.set_title('分數分布 (含 KDE 曲線)')
plt.show()

3.4 熱圖 (Heatmap) — 相關矩陣

# 建立隨機資料矩陣
corr = np.corrcoef(np.random.randn(5, 100))
fig, ax = plt.subplots()
sns.heatmap(corr, annot=True, fmt=".2f", cmap='coolwarm', ax=ax)
ax.set_title('相關係數熱圖')
plt.show()

3.5 Pairplot — 多變量散佈圖與分布

iris = sns.load_dataset('iris')
sns.pairplot(iris, hue='species', height=2.5, palette='bright')
plt.suptitle('Iris 資料集 Pairplot', y=1.02)
plt.show()

4️⃣ 結合 Matplotlib 與 Seaborn

Seaborn 其實是基於 Matplotlib 建構的,兩者可以自由混用。例如,我們可以先用 Seaborn 畫出統計圖,再利用 Matplotlib 進行額外的自訂。

fig, ax = plt.subplots(figsize=(8, 5))

# 使用 Seaborn 畫箱形圖
sns.boxplot(x='class', y='score', data=df, ax=ax, width=0.6)

# 再加上 Matplotlib 的平均線
means = df.groupby('class')['score'].mean()
ax.hlines(means, xmin=-0.4, xmax=0.4, colors='red', linestyles='--', label='平均值')
ax.legend()
ax.set_title('箱形圖 + 平均線 (Matplotlib + Seaborn)')
plt.show()

常見陷阱與最佳實踐

陷阱 說明 最佳實踐
圖表重疊 多次呼叫 plt.show() 或在同一 Figure 中重複繪製會導致圖形堆疊。 使用 fig, ax = plt.subplots(),所有繪圖都指向同一 ax,最後一次 plt.show() 即可。
中文顯示錯亂 預設字型不支援中文,會出現方塊或亂碼。 在程式開頭設定 plt.rcParams['font.sans-serif'] = ['Microsoft JhengHei'](或其他支援中文的字型)。
顏色盲友好 直接使用 plt.cm.jet 等高對比度顏色會對色盲使用者不友好。 使用 Seaborn 的 color_palette('colorblind') 或 Matplotlib 的 viridisplasma
資料量過大 數十萬筆點直接用 scatter 會非常慢。 先做抽樣、或改用 hexbindatashader 等高效能繪圖方式。
圖例過長 同一圖表多條線或多類別會使圖例佔用過多空間。 使用 ax.legend(loc='upper right', fontsize='small') 或分頁顯示。

小技巧

  • tight_layout():自動調整子圖間距,避免標題或座標軸文字被截斷。
  • savefig():若要輸出高解析度圖檔,使用 plt.savefig('fig.png', dpi=300, bbox_inches='tight')
  • plt.style.use():快速套用不同風格(如 ggplotseaborn-darkgrid)。

實際應用場景

  1. 金融時間序列分析

    • 使用 Matplotlib 畫出股價的 K 線圖(candlestick)或移動平均線,結合 Seaborn 的分布圖檢視報酬率的常態性。
  2. 醫療資料探索

    • 透過 Seaborn 的箱形圖與小提琴圖比較不同藥物組的血壓變化,並以 Matplotlib 加入統計檢定結果(p‑value)標註。
  3. 機器學習模型評估

    • 使用 Seaborn 的 pairplot 觀察特徵間的相關性,並以 Matplotlib 繪製 ROC 曲線、混淆矩陣的熱圖,以便快速判斷模型表現。
  4. 行銷儀表板

    • 結合 Matplotlib 的子圖 (subplot2grid) 與 Seaborn 的長條圖、折線圖,製作一頁式的 KPI 報表,並以 savefig 輸出 PDF 供主管審閱。

總結

  • Matplotlib 提供最底層、最彈性的繪圖控制;Seaborn 則在此基礎上加入統計圖形與美觀預設。
  • 只要掌握 Figure → Axes → Plot 的流程,就能快速產出各式圖表;再配合 Seaborn 的 set_themepairplotheatmap 等高階函式,圖表的資訊密度與視覺效果都會大幅提升。
  • 避免常見陷阱(中文字型、顏色盲、資料量過大),並遵循 「先規劃、後實作、最後優化」 的最佳實踐,能讓你的視覺化工作既正確專業

祝你在資料視覺化的道路上,畫出更清晰、更有說服力的圖表!