matplotlib 中使用中文

最近帮师兄画图,要求图中的标注必须是中文,我尝试在画图的 python 文件中直接写入中文,但是会报 warning,说找不到对应的字体:

/data/hanjl/rl-exercise/common/plot_all.py:226: UserWarning: Glyph 19975 (\N{CJK UNIFIED IDEOGRAPH-4E07}) missing from current font.
  plt.tight_layout(pad=0.5)                                                                                                         
/data/hanjl/rl-exercise/common/plot_all.py:236: UserWarning: Glyph 24179 (\N{CJK UNIFIED IDEOGRAPH-5E73}) missing from current font.
  plt.savefig('all.png')

画出来的图,里面的汉子都是小方框…

上网搜了一下,发现这个问题可以解决。参考

我看大家用的基本都是 SimHei 这个字体,我也决定用这个。首先下载 simhei.ttf 这个字体库,有人提供了链接,在 ubuntu 上直接

wget https://raw.githubusercontent.com/zhangsheng377/stats_stock/master/simhei.ttf

matplotlib 会从系统字体库 \usr\share\fonts 和自带字体库 /root/.virtualenvs/py37/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/ttf 两个路径来加载字体,所有加载的字体记录在 /root/.cache/matplotlib/ 中的 json 文件中。

把刚刚下载的 ttf 字体文件放在matplotlib 自带字体路径下面。

然后,打开 ipython,使用下面的指令获得 matplotlib 的 cache 路径:

matplotlib.get_cachedir()

删除原有的 cache

rm -rf /root/.cache/matplotlib

然后,使用下面的命令获得 matplotlib 配置文件的路径

matplotlib.matplotlib_fname()

修改配置文件 matplotlibrc,把下面三行的注释取消,在第二个加上 SimHei,顺序无所谓。

font.family:  sans-serif
#font.style:   normal
#font.variant: normal
#font.weight:  normal
#font.stretch: normal
#font.size:    10.0

#font.serif:      DejaVu Serif, Bitstream Vera Serif, Computer Modern Roman, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif
font.sans-serif:  DejaVu Sans, SimHei, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
#font.cursive:    Apple Chancery, Textile, Zapf Chancery, Sand, Script MT, Felipa, Comic Neue, Comic Sans MS, cursive
#font.fantasy:    Chicago, Charcoal, Impact, Western, Humor Sans, xkcd, fantasy
font.monospace:  DejaVu Sans Mono, Bitstream Vera Sans Mono, Computer Modern Typewriter, Andale Mono, Nimbus Mono L, Courier New, Courier, Fixed, Terminal, monospace

然后打开 ipython,再次 import 一下

import matplotlib.pyplot as plt

查看新产生的 /root/.cache/matplotlib 中的 json 文件是否有 SimHei。有的话说明加载好了。

最后一步,在 python 代码的最后即将画图的时候加上两句。这两句一定要放在这里,我之前放在 python 文件全局开头或者 main 函数开头,结果怎么也不起作用。

    plt.rcParams['font.sans-serif']=['SimHei'] #Show Chinese label
    plt.rcParams['axes.unicode_minus']=False
    plt.tight_layout(pad=0.5)=1, borderaxespad=0.)
    plt.show()
    plt.savefig('all.pdf')
    plt.savefig('all.png')

现在执行 python 代码即可。效果图如下(英文字母格式也变了…):

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值