默認情況下,matplotlib是無法顯示中文的,主要原因是沒有指定中文字體(文件)。因此,有兩種方法,一種是在腳本中指出字體文件,當然這是暫時的,另一種是修改matplotlib的配置文件。
在代碼中指定中文字體
指定確定路徑文件
該方法需要知道字體文件的路徑 :
-
Windows字體文件存儲路徑爲:
C:\Windows\Fonts
-
MacOS字體文件存儲路徑爲:
/System/Library/Fonts
或/Library/Fonts
-
Linux字體文件存儲路徑一般爲:
/usr/share/fonts
或~/.local/share/fonts
指定其他位置字體文件易可,字體文件爲 .tff。
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import matplotlib
zhfont = matplotlib.font_manager.FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf')
plt.xlabel(u"橫座標xlabel",fontproperties=zhfont) #有中文出現的情況,需要u'內容'
使用系統默認中文字體
該方法需要提前查看本地都有哪些中文字體
#coding:utf-8
import matplotlib.pyplot as plt
'''
## 【matplotlib.pyplot在圖形上顯示中文】
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'] ## 中文幼圓
## 以上選擇一條語句即可
'''
plt.rcParams['font.sans-serif']=['SimHei'] ##用來正常顯示中文標籤
plt.rcParams['axes.unicode_minus']=False ##用來正常顯示負號
#有中文出現的情況,需要u'內容'
修改配置文件 一勞永逸
第一步:查詢當前使用的默認樣式文件路徑
import matplotlib
matplotlib.matplotlib_fname() #將會獲得matplotlib默認樣式文件所在文件夾
Windows顯示爲:
'C:\\Users\lemon\\Anaconda3\\lib\\site-packages\\matplotlib\\mpl-data\\matplotlibrc'
Windows設置
方法一:替換文件
- 打開
'C:\Users\lemon\Anaconda3\lib\site-packages\matplotlib\mpl-data'
路徑下的matplotlibrc
文件,找到以#font.serif
開頭這一行,刪除#
取消這一行的註釋,保存文件
font.serif : DejaVu Serif, Bitstream Vera Serif, Computer Modern Roman, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif
- 找到中文字體替換掉matplotlib字體庫中字體(偷樑換柱)
將C:\Windows\Fonts
某一中文字體copy到C:\Users\lemon\Anaconda3\Lib\site-packages\matplotlib\mpl-data\fonts\ttf
中,並刪除ttf
文件夾中存在的一個字體文件,並用文件名重命名copy文件
這一步的作用其實就是將matplotlib中一個默認的字體替換爲我們複製過來的中文字體,將這個中文字體命名改爲matplotlib中有的字體名
3) 重啓python環境
方法二:修改配置文件
1)打開'C:\Users\lemon\Anaconda3\lib\site-packages\matplotlib\mpl-data'
路徑下的matplotlibrc
文件,找到以font.sans-serif
以及#font.family:
開頭這兩行,刪除#
取消註釋,並在font.sans-serif
後添加C:\Windows\Fonts
中存在的中文字體名,保存文件
2)重啓python環境
MacOS設置
1)添加中文字體(*.tff)
參照本節第一步輸出的路徑,將matplotlibrc
替換爲fonts
cd <python庫文件路徑>/site-packages/matplotlib/mpl-data/fonts/tff
將下載或拷貝來的字體文件粘貼到tff
目錄中
2)刪除掉 ~/.matplotlib/下所有緩存文件
rm -rf ~/.matplotlib/*.cache
- 修改文件
vi ~/.matplotlib/matplotlibrc
backend:TkAgg
font.family :sans-serif
font.sans-serif: <添加的字體文件名>
axes.unicode_minus:False
Linux設置
參考Mac
1) 拷貝字體到 usr/share/fonts下:
sudo cp ~/<字體文件名>.tff /usr/share/fonts/<字體文件名>.tff
2) 刪除~/.cache/matplotlib中的緩存文件
rm -rf ~/.cache/matplotlib/*
- 修改配置文件
sudo find -name matplotlibrc
返回結果:
./.virtualenvs/ai/lib/python3.5/site-packages/matplotlib/mpl-data/matplotbrc
打開配置文件:
vi ./.virtualenvs/ai/lib/python3.5/site-packages/matplotlib/mpl-data/matplotbrc
修改其中三項如下:
font.family :sans-serif
font.sans-serif: <添加的字體文件名>
axes.unicode_minus:False