在 Python 使用 Matplotlib 畫圖時,最常遇到的問題就是:
尤其當你要畫圖表並添加標題、座標軸名稱等中文時,常會看到:中文無法顯示,變成方框或亂碼。
□ □ □ □ 或 � � � → 非常影響閱讀。

本篇教學帶你:
- 自動尋找系統中可用的中文字體(Windows / Mac / Linux 都適用)
- 設定 Matplotlib 使用該字體
- 畫出一張標題、標籤都完整顯示中文的折線圖
無論你在公司環境、伺服器(Linux)或自己電腦上,都能直接使用。
🔧 一、為什麼 Matplotlib 常無法顯示中文?
原因很簡單:
Matplotlib 預設只使用西文字體(如 DejaVu Sans)
這些字體並沒有中文字元 → 所以顯示不出中文。
解決方式分兩步:
- 找到一個支援中文字的字體檔(如微軟正黑體 msjh.ttc)
- 告訴 Matplotlib 使用該字體
但不同系統的字體路徑不同,因此我們寫了一段程式碼可以:
自動偵測系統中常用的中文字體 → 自動載入
省去你手動輸入字體路徑的麻煩。
🔍 二、程式範例:自動尋找可用中文字體
以下這段程式會依序檢查 Windows / Mac / Linux 常見的中文字體。
import matplotlib.pyplot as plt
import os
from matplotlib import font_manager as fm
# ===========================================
# 0. 自動尋找可用中文字體
# ===========================================
def find_font():
"""自動尋找系統中文字體"""
possible_fonts = [
# Windows
r"C:\Windows\Fonts\msjh.ttc",
r"C:\Windows\Fonts\msjh.ttf",
r"C:\Windows\Fonts\mingliu.ttc",
r"C:\Windows\Fonts\simhei.ttf",
# Mac
"/System/Library/Fonts/STHeiti Medium.ttc",
"/System/Library/Fonts/PingFang.ttc",
"/Library/Fonts/Arial Unicode.ttf",
# Linux (Noto 字體)
"/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",
"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.otf",
"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
]
for font in possible_fonts:
if os.path.exists(font):
print("✔ 使用中文字體:", font)
return font
raise FileNotFoundError("❌ 找不到可用中文字體,請安裝 Noto Sans CJK 或確認系統字體。")
✔ 這段程式的作用:
- 列出各系統常用的中文字體
- 依序檢查「檔案是否存在」
- 找到字體 → 回傳字體路徑
- 找不到 → 提醒安裝字體
對於開發者來說非常方便,不用再一台電腦一台電腦調整字體路徑。
🧩 三、設定 Matplotlib 使用這個字體
當我們找到中文字體後,就需要設定 Matplotlib 全域使用它:
# 使用找到的字體
font_path = find_font()
font_prop = fm.FontProperties(fname=font_path)
plt.rcParams["font.family"] = font_prop.get_name()
plt.rcParams["axes.unicode_minus"] = False # 避免負號顯示錯誤
✔ 這段程式做了什麼?
設定項目說明font.family設定 Matplotlib 使用你的中文字體axes.unicode_minus=False避免負號「-」顯示成方框
配置完成之後,圖表中的所有中文就能正常呈現!
📈 四、開始畫圖:基本折線圖示範
接下來,我們以最常見的案例——年度銷售額折線圖——做示範。
# ===========================================
# 1. 基本折線圖
# ===========================================
years = [2018, 2019, 2020, 2021, 2022]
sales = [120, 135, 160, 150, 180]
plt.figure(figsize=(6, 4))
plt.plot(years, sales)
plt.title("基本折線圖:年度銷售額")
plt.xlabel("年份")
plt.ylabel("銷售額")
plt.tight_layout()
plt.show()
🖼️ 五、執行後你會看到:
- 標題(含中文)
- X / Y 軸標籤(含中文)
- 折線圖內容
全部都會正確顯示,不再出現亂碼或方框。














