沒想到我會卡一下這個中文字問題
所以這邊特別筆記一下

首先載入需要用的套件

 

import matplotlib
import matplotlib.font_manager as font_manager
import matplotlib.pyplot as plt
import numpy as np

 

 

然後下載字體
我是從 Fontworks Inc. github 上面找的 (不確定是否免費,但是用來測試實驗用應該沒問題)

https://github.com/fontworks-fonts

重點是. 要找 ttf 檔案
我測試如果嘗試載入 woff2 字形會失敗
而目前google github上好像都是woff2 字形?
這我也不是很懂

選好之後就下載字體
這邊我寫如果沒有檔案再下載

 

# 下載字體
![ ! -f "KleeOne-Regular.ttf" ] && wget -q https://github.com/fontworks-fonts/Klee/raw/refs/heads/master/fonts/ttf/KleeOne-Regular.ttf -O KleeOne-Regular.ttf

 

然後重點來了
以下要載入字形檔案之後再列出目前可用字形名稱

 

# 設置字體檔案名稱與載入
font_path = 'KleeOne-Regular.ttf'
matplotlib.font_manager.fontManager.addfont(font_path)

# 注意這邊列出來的字形名稱,需要對應下載的字形實際名稱
for i in sorted(font_manager.get_font_names()):
    print(i)

我這邊列出來是以下這樣:

 

 

DejaVu Sans
DejaVu Sans Display
DejaVu Sans Mono
DejaVu Serif
DejaVu Serif Display
Humor Sans
Klee One
Liberation Mono
Liberation Sans
Liberation Sans Narrow
Liberation Serif
STIXGeneral
STIXNonUnicode
STIXSizeFiveSym
STIXSizeFourSym
STIXSizeOneSym
STIXSizeThreeSym
STIXSizeTwoSym
cmb10
cmex10
cmmi10
cmr10
cmss10
cmsy10
cmtt10

 

可以看到我們剛剛載入的檔案的字形有進去了
然後名稱是 "Klee One"

所以呼叫就要用 "Klee One" 而不是 KleeOne-Regular

然後就可以畫看看了

 

# 設定字形實際名稱
matplotlib.rc('font', family='Klee One')
plt.rcParams['axes.unicode_minus'] = False  # 解決負號顯示問題

# 測試:畫圖並顯示中文
x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.plot(x, y)
plt.title("正弦波 - 測試中文顯示")
plt.xlabel("X 軸")
plt.ylabel("Y 軸")
plt.show()

 

畫出來應該像這樣

給大家參考囉~