CentOs系统matplotlib画图中文乱码

    在集群上使用Python中的matplotlib库画图出现中文乱码,记录一下解决方案。

1. 解决方案

1.1. 步骤一

    获取matplotlibrc文件所在的路径,使用jupyter notebook写代码获取路径。我的文件路径在
/data/WangBeibei/anaconda3/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc

1
2
import matplotlib
matplotlib.matplotlib_fname()

1.2. 步骤二

    

  • 到 anaconda 的 matplotlib 中查看是否有 simhei.ttf 字体
1
2
cd /data/WangBeibei/anaconda3/lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf
ls -al | grep simhei
  • 如果没有输出任何内容,说明没有simhei字体,下载simhei.ttf文件,并上传到/data/WangBeibei/anaconda3/lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf目录下。
  • 修改/data/WangBeibei/anaconda3/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc文件,找到以下3行,改为:
1
2
3
font.family: sans-serif   
font.sans-serif: simhei,DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
axes.unicode_minus: False#解决负号'-'显示为方块的问题
  • 删除/data/WangBeibei/.cache/matplotlib
1
rm -r /data/WangBeibei/.cache/matplotlib

1.3. 步骤三

经过以上步骤,再次运行jupyter notebook程序,中文就不会出现乱码。如果还是出现乱码,添加以下两行代码

1
2
3
4
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['font.sans-serif'] = ['simhei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号#显示所有列
打赏
0%