解决Linux上的jupyterlab缺少SimHei的问题(适用于所有Linux系统)(2023)

简单的说,由于没有对应字体,导入

复制代码
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['font.sans-serif'] = ['SimHei'] 
plt.rcParams['axes.unicode_minus'] = False 

报错

findfont: Font family 'SimHei' not found

此处需要执行

复制代码
import os
import shutil
import urllib.request
import matplotlib

# 设置字体文件的URL和目标文件路径
font_url = "https://github.com/StellarCN/scp_zh/raw/master/fonts/SimHei.ttf"
target_font_path = os.path.join(matplotlib.get_data_path(), "fonts/ttf/SimHei.ttf")

# 下载字体文件
urllib.request.urlretrieve(font_url, target_font_path)

# 找到matplotlibrc文件的路径
matplotlibrc_path = matplotlib.matplotlib_fname()
# 获取matplotlibrc文件所在的文件夹路径
matplotlibrc_dir = os.path.dirname(matplotlibrc_path)

# 找到fonts/ttf目录的路径
fonts_dir = os.path.join(matplotlib.get_data_path(), "fonts/ttf")

# 删除缓存文件夹中的内容
cache_dir = matplotlib.get_cachedir()
shutil.rmtree(cache_dir, ignore_errors=True)

print("字体文件已下载到:", target_font_path)
print("matplotlibrc文件所在目录:", matplotlibrc_dir)
print("删除缓存文件夹:", cache_dir)

进行字体下载和配置,然后需要重启Python内核,此处需要在Jupyter lab中的KERNELS中删除已经存在的活动内核,重新运行ipynb文件(运行后会要求你选择使用什么内核,使用默认的就行了)。

然后字体就没问题了。

这块有自动判断需要下字体文件到哪里和删除哪里的缓存,所以理论上适用于所有Linux系统。

相关推荐
千寻girling4 小时前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
Sheffield7 小时前
Alpine是什么,为什么是Docker首选?
linux·docker·容器
databook7 小时前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风8 小时前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风8 小时前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
helloweilei1 天前
python 抽象基类
python
用户8356290780511 天前
Python 实现 PPT 转 HTML
后端·python
舒一笑1 天前
程序员效率神器:一文掌握 tmux(服务器开发必备工具)
运维·后端·程序员
Johny_Zhao1 天前
centos7安装部署openclaw
linux·人工智能·信息安全·云计算·yum源·系统运维·openclaw