1. 常見報錯 Font family [‘sans-serif’] not found
1.1 報錯現象
在使用 matplotlib 繪圖時,中文設置(如 titile、x label、y label 等)經常出現無法正常展示的問題。我們先來看一個代碼示例,其中 title、x label、y label 均設置爲中文。
# step0:導入畫圖工具包 matplotlib
import matplotlib.pyplot as plt
# step1:手動創建一個figure對象,相當於一個空白的畫布
figure = plt.figure()
# step2:字體基本設置
plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默認字體
plt.rcParams['axes.unicode_minus'] = False # 解決保存圖像是負號'-'顯示爲方塊的問題
# step3:在畫布上添加一個座標系,標定繪圖位置
axes1 = figure.add_subplot(1, 1, 1)
# step4:準備畫圖的數據
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [21, 27, 29, 32, 29, 28, 35, 39, 49]
# step5:設置基本信息
axes1.set_xlabel('X軸')
axes1.set_ylabel('Y軸')
axes1.set_title("圖片標題")
# step6:畫圖,設置線條顏色、線型、點標記符
axes1.plot(x, y, color='red', linestyle='-.', marker='*')
# step7:展示
plt.show()
上面下代碼示例執行結果如下圖所示,中文設置展示爲“口”,與此同時,程序執行過程中也會報錯,信息如下。
報錯信息:
findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans.
1.2 報錯原因
sans-serif 是無襯線字體,是一種通用字體族,常見的中文無襯線字體有:宋體(STSong), 黑體(SimHei), 楷體(Kaiti),隸書(Lisu), 仿宋(FangSong), 幼圓(YouYuan),微軟雅黑(Microsoft YaHei)等。之所以出現上面的報錯,根本原因在於運行程序的機器上沒有對應的字體配置。原因清楚了,問題也就好解決了——下載對應的字體文件,放置於指定的文件目錄下並進行配置即可。
1.3 解決方案
步驟-1: 下載需要的字體文件
本文以黑體(SimHei)爲例,下載對應的字體文件 “SimHei.ttf”,下載地址
步驟-2: 將下載的字體文件放到指定目錄下
- 通過執行如下代碼,獲取字體文件路徑信息。
import matplotlib
print(matplotlib.matplotlib_fname())
上述代碼執行結果:
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/matplotlib/mpl-data/matplotlibrc
- 將字體文件放置於如下文件目錄(不同的操作系統略有差異):
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/matplotlib/mpl-data/fonts/ttf 。
步驟-3: 刪除 matplotlib 的緩衝目錄
- 通過執行如下代碼,獲取緩衝目錄路徑信息。
import matplotlib
print(matplotlib.get_cachedir())
- 執行命令刪除緩存目錄。
對於 Linux、Mac OX 類型操作系統,可以直接使用命令“rm -rf 路徑” 刪除緩存,對於 Windows 系統可以手動刪除。本文所示的例子中,刪除命令爲:
rm -rf /Users/guojin/.matplotlib
步驟-4: 修改文件 matplotlibrc,增加配置
這一步非常關鍵,很多時候配置不生效,都是由於此步驟缺失。修改 matplotlibrc 文件
修改/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/matplotlib/mpl-data/matplotlibrc,修改內容有三處,如下所示:
# 1.去掉前面的 # 號,這是一個註解符
font.family : sans-serif
# 2.去掉前面的 # 號,並在冒號後面添加 SimHei
font.sans-serif : SimHei, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
# 3.去掉前面的 # 號,並將True改爲False
axes.unicode_minus : False
步驟-5: 重啓集成開發環境-IDE
經過上述步驟,基本大功告成,重啓集成開發環境-IDE(Eclipse、IntelliJ IDEA等),重新運行程序即可正常顯示。注意:重啓大多數時候都是必要的!!!
1.4 問題修復後的執行結果
2. matplotlib 字體設置
2.1 設置字體的類型
在上一節的例子中已經介紹了字體的設置方法,這裏重新回顧一下。
# 字體基本設置
plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定字體
plt.rcParams['axes.unicode_minus'] = False # 解決保存圖像是負號'-'顯示爲方塊的問題
除了 SimHei 之外,常用的中文字體還有很多,設置方式如下:
plt.rcParams['font.sans-serif']=['STSong'] ## 中文宋體
plt.rcParams['font.sans-serif']=['SimHei'] ## 中文黑體
plt.rcParams['font.sans-serif']=['Kaiti'] ## 中文楷體
plt.rcParams['font.sans-serif']=['Lisu'] ## 中文隸書
plt.rcParams['font.sans-serif']=['FangSong'] ## 中文仿宋
plt.rcParams['font.sans-serif']=['YouYuan'] ## 中文幼圓
2.2 設置字體的格式
通過執行如下代碼,獲取字體文件路徑信息。
import matplotlib
print(matplotlib.matplotlib_fname())
通過上述代碼,獲得字體文件路徑爲:
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/matplotlib/mpl-data/matplotlibrc
文件 matplotlibrc 中有一段默認的配置,如下所示:
#font.style : normal
#font.variant : normal
#font.weight : normal
#font.stretch : normal
#font.size : 10.0
在實際應用中,我們可以通過修改上述配置,或者在代碼中直接設置實現字體格式控制。其中,字體的 style 和 weight 有如下選項:
# 字體粗細、類型
styles=['normal','italic','oblique']
weights=['light','normal','medium','semibold','bold','heavy','black']