欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 八卦 > cloudstudio腾讯云:matplotlib 设置中文字体

cloudstudio腾讯云:matplotlib 设置中文字体

2025/6/14 12:22:21 来源:https://blog.csdn.net/dsbss/article/details/148546165  浏览:    关键词:cloudstudio腾讯云:matplotlib 设置中文字体

检查可用字体:

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

在这里插入图片描述

# 列出所有中文字体文件
!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(根据包管理器选择)

设置字体(局部)

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 中验证字体是否可用

import matplotlib.pyplot as plt# 测试字体是否可用(以黑体为例)
try:plt.title("测试中文标题", fontproperties=font)  # 若显示正常,则字体可用plt.show()
except Exception as e:print(f"字体设置失败:{e}")

在这里插入图片描述

设置字体(全局)

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 中验证字体是否可用

import matplotlib.pyplot as plt# 测试字体是否可用(以黑体为例)
try:plt.title("测试中文标题")  # 若显示正常,则字体可用plt.show()
except Exception as e:print(f"字体设置失败:{e}")

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词