jupyter matplotlib 中文报错/乱码

在 jupyter 中使用 matplotlib 进行画图的时候, 如果包含中文, 会有一堆报错, 并且输出的图片中的中文也无法正常显示.

解决方案:

  1. 查找支持的中文字体
import matplotlib.font_manager as fm

# matplotlib only know these fonts
font_list = [f for f in fm.fontManager.ttflist]

# check font names what you want
# 'CJK', 'Han', , 'TW'
cjk_list = ['CN']

for f in font_list:
    if any(s.lower() in f.name.lower() for s in cjk_list):
        print(f'name={f.name}, path={f.fname}')

输出结果:

name=AR PL UMing CN, path=/usr/share/fonts/cjkuni-uming/uming.ttc

如果没有结果, 则需要去下载安装字体

  1. 设置字体

在输出结果中, 找一个 name 的值进行设置:

%matplotlib inline

plt.rc('font', family='AR PL UMing CN')

matplotlib 的图中, 中文就可以正常显示了

如果依然不行, 尝试删除 rm -rf ~/.matplotlib/font* or rm -rf ~/.cache/.matplotlib/fontl*. 重启 jupyter

如果还是不行

如果各种尝试还是不行, 可以尝试以下方法

命令行下载字体:

wget 'https://labfileapp.oss-cn-hangzhou.aliyuncs.com/clouder/simsun.tar.gz'
# 新建目录
mkdir /usr/share/fonts/chinese
#解压中文字体包
tar -xzf simsun.tar.gz 
#移动中文字体文件
mv simsun/* /usr/share/fonts/chinese
# 更改目录权限
chmod -R 755 /usr/share/fonts/chinese/

python 修改 matplotlib 的 font_manager

import matplotlib.font_manager

# 加载自定义字体文件
custom_font_path = '/usr/share/fonts/chinese/SimHei.ttf'
matplotlib.font_manager.fontManager.addfont(custom_font_path)
plt.rcParams['font.sans-serif'] = ['SimHei']
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值