matplotlib繪圖不顯示中文


媽的 anaconda 版本太低,導致matlotlib 畫圖不清晰, 換個就好了,不然圖形總是一坨
wget https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/Anaconda3-2019.07-Linux-x86_64.sh


import pandas as pd
import numpy as np
from pandas import Series, DataFrame
%matplotlib inline
%config InlineBackend.figure_format = 'svg'

操作

下載字體

http://wt4.jb51.net:81/201509/tools/simhei(jb51.net).rar
http://down.font5.com.cn/fontfile/200903/simheittf.rar
http://www.font5.com.cn/font_download.php?id=151&part=1237887120
http://www.font5.com.cn/font_download.php?id=151&part=1237887120

獲取matplotlib的配置文件位置

import matplotlib
print(matplotlib.matplotlib_fname())

#獲取到文件:
/home/data/anaconda3/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc
##修改
vim /home/data/anaconda3/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc
font.family         : sans-serif

font.sans-serif     : SimHei, DejaVu Sans, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif(在font.sans-serif后添加SimHei,用來正常顯示中文標簽)

axes.unicode_minus  : False(把True改為False,用來正常顯示負號)

獲取matplotlib 字體庫位置

locate -b 'mpl-data'

/home/data/anaconda3/lib/python3.6/site-packages/matplotlib/mpl-data
/home/data/anaconda3/pkgs/matplotlib-2.2.2-py36h0e671d2_1/lib/python3.6/site-packages/matplotlib/mpl-data

將字體文件復制到這兩個路徑下。
終端下運行命令fc-list :lang=zh-cn (不知道是干啥的)

找到家目錄 .cache/matplotlib目錄將matplotlib刪除

方法1:改了配置之后並不會生效,需要重新加載字體,在notebook中運行如下代碼即可
from matplotlib.font_manager import _rebuild
rebuild() #重新加載一下
2)方法2:如果上面方法1試了以后,還不行。重啟電腦。

重啟機器

以下沒有測試過.

下載中文字體:
http://www.font5.com.cn/font_download.php?id=151&part=1237887120

將下載的字體ttf文件放到matplotlib的字體庫位置:
anaconda3/lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf/

刪除matplotlib的字體緩存,文件位置:
mpl.get_cachedir()–>獲取字體cache位置的方法(應該有獲取其他配置的方法)
.cache/matplotlib/fontList.json
該文件刪除后,會自動生成,重新查找解析字體庫,並生成這個文件

代碼中的修改:
rcParams[‘font.family’] = ‘sans-serif’ #用來正常顯示中文
rcParams[‘font.sans-serif’] = [‘SimHei’] #用來正常顯示負號

永久修改:
mpl.matplotlib_fname() –>獲取配置文件的方法
可在matplotlib的配置文件中修改:/home/rickey/anaconda3/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc
其中有font.family和font.sans-serif的配置項

font.family和font.sans-serif的聯系:
font.family是一個字體集,其中包含多種字體,比如sans-serif表示中文,中文可以有多種字體,比如正楷,宋體等
SimHei :黑體
SimSun :宋體
以上具體的某一種字體可以在字體網站上下載,並安裝。

參考:https://www.jianshu.com/p/240ea3ae0dc9


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM