Matplotlib 是 Python 科學繪圖的基石。本文以漸進式範例,帶你從基本折線圖出發,掌握多線圖、樣式客製、中文顯示、圖例、子圖與匯出圖檔等核心技能。
pip install matplotlib numpy
# 中文顯示需額外安裝字型 (Windows 內建微軟正黑體,Linux 需安裝 noto-fonts-cjk)
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 1, 5, 3]
plt.plot(x, y)
plt.title('我的第一張圖')
plt.xlabel('X 軸')
plt.ylabel('Y 軸')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# 設定中文字型 (Windows)
plt.rcParams['font.sans-serif'] = ['Microsoft JhengHei']
plt.rcParams['axes.unicode_minus'] = False # 正常顯示負號
x = np.linspace(0, 2*np.pi, 50)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.sin(x) * np.cos(x)
plt.figure(figsize=(10, 6), dpi=100)
# 線條樣式字串: '[顏色][標記][線型]'
# 顏色: b/g/r/c/m/y/k/w | 標記: o/s/^/v/>/*/+/x/D/d | 線型: -/--/-./:/
plt.plot(x, y1, 'b-o', label='sin(x)', linewidth=2, markersize=4, markevery=5)
plt.plot(x, y2, 'r--s', label='cos(x)', linewidth=2, markersize=4, markevery=5)
plt.plot(x, y3, 'g:^', label='sin(x)cos(x)', linewidth=2, markersize=4, markevery=5)
plt.title('三角函數比較')
plt.xlabel('弧度 (rad)')
plt.ylabel('振幅')
plt.grid(True, linestyle='--', alpha=0.6)
plt.legend(loc='upper right', framealpha=0.9)
plt.tight_layout() # 自動調整邊距防止標籤被切
# 儲存向量圖 (出版級) 與點陣圖
plt.savefig('trig_functions.pdf', bbox_inches='tight')
plt.savefig('trig_functions.png', dpi=300, transparent=True)
plt.show()
fig, axes = plt.subplots(2, 2, figsize=(12, 8), sharex=True, sharey=True)
# axes 是 2x2 的 Axes 陣列
data = {
'sin': np.sin(x),
'cos': np.cos(x),
'tan': np.tan(x),
'sinc': np.sinc(x/np.pi)
}
for ax, (name, y) in zip(axes.flat, data.items()):
ax.plot(x, y, label=name)
ax.set_title(name)
ax.grid(True, alpha=0.3)
ax.legend(fontsize='small')
fig.suptitle('四圖同現', fontsize=16)
plt.tight_layout(rect=[0, 0, 1, 0.96]) # 留空給 suptitle
plt.savefig('subplots_demo.png', dpi=150)
plt.show()
| 需求 | API / 參數 |
|---|---|
| 線條顏色 | color='#1f77b4' 或 'b'、'#FF5733'、(0.1, 0.5, 0.9) |
| 線寬 | linewidth=2 或 lw=2 |
| 標記樣式 | marker='o', marker='s', marker='*' |
| 標記大小 | markersize=6 或 ms=6 |
| 標記間隔 | markevery=10 (每 10 點標一個) |
| 線型 | linestyle='--' 或 ls=':' |
| 透明度 | alpha=0.7 |
| 填充區域 | ax.fill_between(x, y1, y2, alpha=0.2) |
| 雙 Y 軸 | ax2 = ax.twinx() |
| 對數座標 | ax.set_yscale('log') / ax.loglog() |
| 極座標 | fig.add_subplot(projection='polar') |
| 3D 繪圖 | from mpl_toolkits.mplot3d import Axes3D; ax = fig.add_subplot(projection='3d') |
# 方法 1: rcParams 全域設定 (推薦)
import matplotlib
matplotlib.rcParams['font.sans-serif'] = ['Microsoft JhengHei', 'PingFang TC', 'Noto Sans CJK TC', 'sans-serif']
matplotlib.rcParams['axes.unicode_minus'] = False
# 方法 2: 單一文字指定 fontproperties
from matplotlib.font_manager import FontProperties
font = FontProperties(fname='C:/Windows/Fonts/msjh.ttc', size=12)
plt.title('中文標題', fontproperties=font)
# 方法 3: 環境變數 (Linux/Docker)
# export MPLBACKEND=agg
# 確認字型: fc-list :lang=zh
dpi=300 列印級。transparent=True (僅 PNG/SVG 支援)。ax.plot(x, y, ',') (像素標記) 或 datashader / bokeh / plotly 互動式庫。matplotlib.animation.FuncAnimation + blit=True。plt.ioff() 批量生成圖片時加速。