解决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系统。

相关推荐
π大星星️42 分钟前
基于LNMP架构的个人博客系统部署
服务器·架构
码上淘金4 小时前
【Python】Python常用控制结构详解:条件判断、遍历与循环控制
开发语言·python
Brilliant Nemo4 小时前
四、SpringMVC实战:构建高效表述层框架
开发语言·python
孙克旭_4 小时前
PXE_Kickstart_无人值守自动化安装系统
linux·运维·自动化
2301_787552875 小时前
console-chat-gpt开源程序是用于 AI Chat API 的 Python CLI
人工智能·python·gpt·开源·自动化
懵逼的小黑子5 小时前
Django 项目的 models 目录中,__init__.py 文件的作用
后端·python·django
皓月盈江5 小时前
Linux电脑本机使用小皮面板集成环境开发调试WEB项目
linux·php·web开发·phpstudy·小皮面板·集成环境·www.xp.cn
Y3174295 小时前
Python Day23 学习
python·学习
深井冰水5 小时前
mac M2能安装的虚拟机和linux系统系统
linux·macos
leoufung6 小时前
内核内存锁定机制与用户空间内存锁定的交互分析
linux·kernel