关于Matplotlib画图出现的中文显示为方框的问题,网上的很多解决方案是针对Windows系统的:
import matplotlib.pyplot as plt plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签 plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
在Linux会出现问题的主要原因是matplotlib找不到相应的中文字体。
解决方案:
1. 将Windows中的中文字体安装进Linux。
比如将simfang.ttf、simkai.ttf复制到/usr/share/font目录下即可
是否安装成功可通过以下命名查看:
jovyan@9f5db12af44c:~$ fc-list :lang=zh /usr/share/fonts/simkai.ttf: KaiTi,楷体:style=Regular,Normal,obyčejné,Standard,Κανονικά,Normaali,Normál,Normale,Standaard,Normalny,Обычный,Normálne,Navadno,Arrunta /usr/share/fonts/simfang.ttf: FangSong,仿宋:style=Regular,Normal,obyčejné,Standard,Κανονικά,Normaali,Normál,Normale,Standaard,Normalny,Обычный,Normálne,Navadno,Arrunta
2. 将上述字体复制到matplotlib字体目录下
查询路径的方式为:
import matplotlib as mpl print(mpl.matplotlib_fname())
打印的内容为:/opt/conda/lib/python3.7/site-packages/matplotlib/mpl-data/matplotlibrc
则字体目录为:/opt/conda/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/ttf
4. 修改配置文件
配置文件即为刚才查询得到的/opt/conda/lib/python3.7/site-packages/matplotlib/mpl-data/matplotlibrc
打开后去除下面三个配置项的注释,并将添加的字体英文名条件到font.sans-serif的最前面
font.family : sans-serif font.sans-serif :FangSong, Kaiti, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif axes.unicode_minus : True ## use unicode for the minus symbol ## rather than hyphen. See ## http://en.wikipedia.org/wiki/Plus_and_minus_signs#Character_codes
4、删除缓存
一般情况下,缓存在~/.cache/matplotlib目录下,但也有些会在~/.matplotlib目录下。直接执行如下命令即可。
rm -rf ~/.cache/matplotlib rm -rf ~/.matplotlib
最后重新执行我们的程序即可正常显示中文。
网友评论已有0条评论, 我也要评论