最近帮师兄画图,要求图中的标注必须是中文,我尝试在画图的 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')
画出来的图,里面的汉子都是小方框…
上网搜了一下,发现这个问题可以解决。参考
- https://blog.csdn.net/fwj_ntu/article/details/105598145
- https://www.jianshu.com/p/367e85c2b2f9
- https://blog.csdn.net/BigData_Mining/article/details/111656101
我看大家用的基本都是 SimHei
这个字体,我也决定用这个。首先下载 simhei.ttf 这个字体库,有人提供了链接,在 ubuntu 上直接
wget https:
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 代码即可。效果图如下(英文字母格式也变了…):
Original: https://blog.csdn.net/weixin_43742643/article/details/127769948
Author: hanjialeOK
Title: matplotlib 中使用中文
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/767911/
转载文章受原作者版权保护。转载请注明原作者出处!