matplotlib – 在linux环境配置jupyter支持中文

默认情况下,jupyter中matplotlib绘制的图片无法正确显示中文,这需要自行配置,我参考了网上的教程,实测有效且简单。

下载SimHei中文字体文件

点我直接下载,将字体文件拷贝到linux服务器上待用。

移动simhei字体文件

在linux上打开python,查看matplotlib包所在目录:

因此,我们将simhei.ttf文件,移动到matplotlib包的字体目录下:

mv ~/simhei.ttf /usr/local/miniconda3/envs/jupyter/lib/python3.8/site-packages/matplotlib/mpl-data/fonts/ttf/

配置matplotlib支持simhei字体

最后,我们打开上述/usr/local/miniconda3/envs/jupyter/lib/python3.8/site-packages/matplotlib/mpl-data/matplotlibrc配置文件,编辑如下2个字段即可。

axes.unicode_minus: False

将上述字段注释打开,改为False

font.sans-serif: SimHei, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
# zapf chancery, charter, serif, sans-serif, helvetica,

将上述字段注释打开,加入SimHei

清空matplotlib缓存

在linux上执行python,获取matplotlib的配置缓存目录:

然后删除该目录:rm -rf /root/.cache/matplotlib

重启jupyter

重启jupyter,然后绘制带有中文的matplotlib图片,中文立即正常展示,无需额外配置。

 

如果文章帮助您解决了工作难题,您可以帮我点击屏幕上的任意广告,或者赞助少量费用来支持我的持续创作,谢谢~