检查可用字体:
python
import matplotlib.font_manager as fm
fonts = [f.name for f in fm.fontManager.ttflist]
print(fonts) # 查看系统中可用的字体列表

python
# 列出所有中文字体文件
!fc-list :lang=zh

没有中文字体,需要下载
!sudo apt-get install fonts-wqy-microhei -y # 文泉驿微米黑
检查sudo安装
python !dpkg -s sudo 2>/dev/null || echo "sudo 未安装"
如果没安装执行下面命令,安装sudo
python 安装 sudo(根据包管理器选择)
设置字体(局部)
python
from matplotlib.font_manager import FontProperties
# 指定中文字体路径
font_path = "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc"
font = FontProperties(fname=font_path)
路径按照
!fc-list :lang=zh
查到的
在 Python 中验证字体是否可用
python
import matplotlib.pyplot as plt
# 测试字体是否可用(以黑体为例)
try:
plt.title("测试中文标题", fontproperties=font) # 若显示正常,则字体可用
plt.show()
except Exception as e:
print(f"字体设置失败:{e}")

设置字体(全局)
python
from pathlib import Path
# 字体文件路径(根据实际情况修改)
font_path = Path("/usr/share/fonts/truetype/wqy/wqy-microhei.ttc")
# 将字体文件添加到 Matplotlib 的字体缓存
fm.fontManager.addfont(str(font_path))
# 获取字体名称(用于全局设置)
font_name = fm.FontProperties(fname=str(font_path)).get_name()
# 全局设置字体
plt.rcParams["font.family"] = font_name
在 Python 中验证字体是否可用
python
import matplotlib.pyplot as plt
# 测试字体是否可用(以黑体为例)
try:
plt.title("测试中文标题") # 若显示正常,则字体可用
plt.show()
except Exception as e:
print(f"字体设置失败:{e}")