RuntimeWarning: Glyph missing from current font. font.set_text(s, 0, flags=flags)

D:\miniconda3\envs\tf\lib\site-packages\matplotlib\backends\backend_agg.py:180: RuntimeWarning: Glyph 39321 missing from current font.
  font.set_text(s, 0, flags=flags)
D:\miniconda3\envs\tf\lib\site-packages\matplotlib\backends\backend_agg.py:180: RuntimeWarning: Glyph 28207 missing from current font.
  font.set_text(s, 0, flags=flags)
D:\miniconda3\envs\tf\lib\site-packages\matplotlib\backends\backend_agg.py:180: RuntimeWarning: Glyph 28040 missing from current font.
  font.set_text(s, 0, flags=flags)
D:\miniconda3\envs\tf\lib\site-packages\matplotlib\backends\backend_agg.py:180: RuntimeWarning: Glyph 38450 missing from current font.
  font.set_text(s, 0, flags=flags)
D:\miniconda3\envs\tf\lib\site-packages\matplotlib\backends\backend_agg.py:180: RuntimeWarning: Glyph 34389 missing from current font.
  font.set_text(s, 0, flags=flags)

在这里插入图片描述
警告原因,plt 画图是找不到字体,需要手动设置:

plt.rcParams['font.sans-serif']=['SimHei'] #显示中文标签
plt.rcParams['axes.unicode_minus']=False

结果

在这里插入图片描述
发现图中原本缺失的中文回来了!

### 问题分析 警告信息 `RuntimeWarning: Glyph 8722 missing from current font` 表示当前使用的字体缺少某个字符(此处为 Unicode 编码 8722,即“−”符号),通常出现在使用 `matplotlib` 绘图时尝试渲染中文或特殊字符的情况下。此问题可以通过配置字体支持、设置默认字体或清除字体缓存等方法解决。 ### 解决方案 #### 1. 设置支持中文的字体 可以通过设置 `font.sans-serif` 参数为支持中文的字体名称,例如 `SimHei`(黑体)或 `KaiTi`(楷体),以确保字符能够正确渲染: ```python import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置黑体 plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题 ``` 该方法可确保中文字符和特殊符号(如“−”)在图形中正常显示[^5]。 #### 2. 修改 `matplotlibrc` 文件以永久生效 若希望字体设置对所有绘图脚本永久生效,可修改 `matplotlib` 的配置文件 `matplotlibrc`,找到并修改以下字段: ```ini font.family : sans-serif font.sans-serif : SimHei, DejaVu Sans, Bitstream Vera Sans, ... # 添加 SimHei axes.unicode_minus : False # 禁用 Unicode 负号显示 ``` 修改完成后,清除字体缓存文件以确保新设置生效。 #### 3. 清除字体缓存 `matplotlib` 会缓存字体信息,修改字体后需手动清除缓存文件,路径如下: - Windows:`C:\Users\用户名\.matplotlib\fontList.cache` - Linux/macOS:`~/.cache/matplotlib/fontList.cache` 清除缓存后重新运行绘图脚本,字体更改将生效[^4]。 #### 4. 使用系统支持的字体 可以通过以下代码查看当前系统支持的字体列表,并选择合适的字体进行配置: ```python import matplotlib.font_manager fonts = sorted([f.name for f in matplotlib.font_manager.fontManager.ttflist]) print(fonts) ``` 若列表中未包含所需字体,可手动下载并安装字体文件,然后将其放入 `matplotlib` 字体目录中,再清除缓存[^2]。 #### 示例代码 以下是一个完整的绘图示例,包含字体设置和中文标签: ```python import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False plt.plot([1, 2, 3], [1, 4, 9], label="示例曲线") plt.title("中文标题") plt.xlabel("X轴") plt.ylabel("Y轴") plt.legend() plt.show() ``` ---
评论 24
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

颹蕭蕭

白嫖?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值