Linux下Python通过matplotlib中文字体乱码

环境

pyenv python =3.7.0
matplotlib = 3.4.3
OS = Ubuntu 16.04

报错

文字会显示为一些小方框
由于已解决问题,无此显示效果,图片引用自 matplotlib轻松解决中文乱码问题

解决

查看matplotlib配置文件位置,方便后续配置
In [1]: import matplotlib

In [2]: matplotlib.matplotlib_fname()
Out[2]: '/root/.pyenv/versions/3.7.3/lib/python3.7/site-packages/matplotlib/mpl-data/matplotlibrc'
首先查看系统内是否有中文字体
fc-list :lang=zh
# 如果没有fc-list命令,则通过以下命令行进行安装
apt install fontconfig
如果没有回显,可以在本地找一个,或者网上下载一个SimHei
上传到/usr/share/fonts路径下创建自己的字体文件夹,并将文件传入此文件夹中,如果没有此文件夹创建。
cd /usr/share/fonts/yourfontdir
mv simhei.ttf /usr/share/fonts/yourfontdir
上传完毕,在服务器中安装存放的字体,mkfontscale 和 mkfontdir
apt install fontconfig mkfontscale
#生成字体索引信息. 会显示字体的font-family
sudo mkfontscale
sudo mkfontdir
fc-cache	#更新字体缓存
然后修改matplotlibrc文件配置
cp /usr/share/fonts/yourfontdir/simhei.ttf /root/.pyenv/versions/3.7.3/lib/python3.7/site-packages/matplotlib/mpl-data/matplotlibrc
#删除缓冲目录
rm -rf ~/.cache/matplotlib
#如果有字体,绘图还是显示小方块,则需要强力删除
rm -rf ~/.matplotlib/*.cache

此时字体已经存在于服务器,配置改了之后不会生效,需要在python内重新加载,即:

 

python console:
from matplotlib.font_manager import _rebuild
_rebuild() #reload一下
我在此matplotlib版本没有找到_rebuild,重启jupyter即可生效,中文效果图如下
原文地址:https://www.cnblogs.com/gaodp/p/15291584.html