解决docker部署的jupyter容器中matplotlib中文乱码

narcissuskid
发布于 2023-09-15 / 85 阅读 / 0 评论 / 0 点赞

解决docker部署的jupyter容器中matplotlib中文乱码

问题描述:使用docker部署的jupyter容器中matplotlib中文乱码

1. 下载字体

wget https://github.com/StellarCN/scp_zh/raw/master/fonts/SimHei.ttf

2. 获取matplotlib相关目录

import matplotlib
matplotlib.matplotlib_fname()

此处以/home/jovyan/.local/lib/python3.7/site-packages/matplotlib/mpl-data/matplotlibrc为例

3. 进入jupyter容器

sudo docker exec --user root -it <容器id> /bin/bash

3.1 将字体文件放到对应目录

cp  ~/work/taptap/SimHei.ttf  /home/jovyan/.local/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/ttf/

3.2 编辑配置文件

vi /home/jovyan/.local/lib/python3.7/site-packages/matplotlib/mpl-data/matplotlibrc

在配置文件中修改如下内容

font.family:  sans-serif   #去掉注释
font.sans-serif: simhei, DejaVu Sans, Bitstream Vera Sans #去掉注释,并增加simhei
axes.unicode_minus: False #去掉注释,并将True改为False

3.3 清除缓存

在jupyter运行如下代码,获得缓存目录

matplotlib.get_cachedir()

在容器命令行中运行如下代码,清除缓存

rm -rf /home/jovyan/.cache/matplotlib

4. 重启jupyter

5. jupyter设置字体

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['simhei']
plt.rcParams['axes.unicode_minus'] = False

检查效果

参考: https://blog.csdn.net/chenlei456/article/details/123995303


评论