萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python Matplotlib 繪圖入門:從單線圖到多線圖、圖例、儲存圖檔

前言

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()

物件導向 API (Axes 介面) — 推薦用於複雜圖表

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

匯出格式選擇指南

  • PDF/SVG:向量格式,放大不失真,適合論文、報表、列印。
  • PNG:點陣格式,Web 發布、文件嵌入首選;dpi=300 列印級。
  • JPG:有損壓縮,檔案較小,不適合線條圖 (會有伪影)。
  • 透明背景:transparent=True (僅 PNG/SVG 支援)。

效能優化技巧

  • 大量資料點 (>10萬) 使用 ax.plot(x, y, ',') (像素標記) 或 datashader / bokeh / plotly 互動式庫。
  • 動畫請用 matplotlib.animation.FuncAnimation + blit=True。
  • 關閉互動模式 plt.ioff() 批量生成圖片時加速。
copyright © 萬盛學電腦網 all rights reserved