解决Linux系统中python matplotlib画图的中文显示问题

运行环境:

  • python3.7
  • Linux Centos7
  • 用conda安装的matplotlib

问题:

  • matplotlib画图,无法显示中文

问题原因:

  • linux操作系统以及matplotlib的字体库中,没有可用的中文字体
  • matplotlib包默认只支持ASCII码,不支持unicode码

解决方案:

其实也是综合了网上的各种解决方案。总体说来有以下几个步骤:

1. 获取matplotlibrc文件所在路径。我这里使用远程jupyter notebook获取:

import matplotlib
matplotlib.matplotlib_fname()

例如,我的这个文件在: 

'/root/anaconda3/lib/python3.7/site-packages/matplotlib/mpl-data/matplotlibrc'

后续步骤会修改此文件中的font参数。

2. 看看系统中的所有字体,以及可用的中文字体。也是在jupyter nb中:

from matplotlib.font_manager import FontManager
import subprocess

fm = FontManager()
mat_fonts = set(f.name for f in fm.ttflist)
print (mat_fonts)
output = subprocess.check_output('fc-list :lang=zh -f "%{family}\n"', shell=True)
print ('*' * 10, '系统可用的中文字体', '*' * 10)
print (output)
zh_fonts = set(f.split(',', 1)[0] for f in output.decode().split('\n'))
available = mat_fonts & zh_fonts
print ('*' * 10, '可用的字体', '*' * 10)
for f in available:
    print(f)

做完上述操作,会发现“可用的字体”这里为空。因为没有中文字体给matplotlib用(所以才会中文都显示“框框”)

3. 假设操作系统中没有中文字体。此时下载一个ttf中文字体,并在cenos中安装。要安装那种系统能检测font-family的,否则无效。我在这个网站下载的:http://font.chinaz.com/130130474870.htm

解压rar文件。在 /usr/share/fonts 路径下创建存放此字体的文件夹myfonts,并下载的ttf文件复制到myfonts中(可以给文件改个英文名,方便操作)

4. 给cenos安装这个字体。

先yum install -y fontconfig mkfontscale

然后

cd  /usr/share/fonts/myfonts

#生成字体索引信息. 会显示字体的font-family

sudo mkfontscale

sudo mkfontdir

#更新字体缓存:

fc-cache

 

5. 修改matplotlibrc文件

修改步骤1中获取的matplotlibrc文件配置。去掉下面注释,并修改

font.family         : sans-serif        
font.sans-serif     : WenQuanYi Zen Hei Mono, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif     
就是知道字库族为sans-serif,同时添加“SimHei”即宋体到字库族列表中,同时将找到
axes.unicode_minus,将True改为False,作用就是解决负号'-'显示为方块的问题

6. 这一步骤最重要!为matplotlib增加中文字体

完成步骤5后,再操作步骤2,会发现“可用的中文字体”已经有了刚才安装的字体,但是画图仍然不能显示中文。这是因为你这个字体给centos安装了、也告诉matplotlib要用这个字体了,但是,matplotlib找不到这个字体的ttf文件,所以需要将下载的ttf字体复制一份到以下路径:

 /root/anaconda3/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/ttf

并删除相关cache

rm -rf ~/.matplotlib/*.cache

删除其中与字体有关的cache 

7. 现在重新画个图试试 

 

参考

https://www.jianshu.com/p/7b7a3e73ef21

https://blog.csdn.net/dgatiger/article/details/50414549

另一种方式是将想使用的字体命名为DejaVuSans.ttf替换上述路径下的DejaVuSans.ttf即可

https://blog.csdn.net/u013617229/article/details/82632751

  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值