解决 PyCharm 2024.1+ matplotlib 图表显示异常:Plots 工具窗口空白 / tostring_rgb 报错
问题现象
在 PyCharm 2024.1.x Professional 中运行 matplotlib 绑图脚本时,出现以下报错:
AttributeError: 'FigureCanvasInterAgg' object has no attribute 'tostring_rgb'.
Did you mean: 'tostring_argb'?
同时 PyCharm 右侧的 Plots 工具窗口不显示,或显示空白/花屏。
根本原因
PyCharm 2024.1.x 自带的 matplotlib 后端文件:
<PyCharm安装目录>/plugins/python/helpers/pycharm_matplotlib_backend/backend_interagg.py
该文件第 85 行调用了 self.tostring_rgb(),这是 matplotlib 的旧版 API。
从 matplotlib 3.9 开始,tostring_rgb() 被移除,官方推荐使用 buffer_rgba()。但 PyCharm 2024.1.7 在发布时没有同步更新这个后端文件,导致新版本 matplotlib 与 PyCharm 内置后端不兼容。
这不是用户配置问题,而是 PyCharm 的 bug------它的辅助文件没有跟上 matplotlib 的 API 变更。
解决方案
方法一:修改 PyCharm 后端文件(推荐)
找到你 PyCharm 安装目录下的 backend_interagg.py 文件:
Windows:
D:\...\PyCharm 2024.x.x\plugins\python\helpers\pycharm_matplotlib_backend\backend_interagg.py
macOS:
/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm_matplotlib_backend/backend_interagg.py
Linux:
~/.local/share/JetBrains/Toolbox/apps/PyCharm/ch-0/xxx/plugins/python/helpers/pycharm_matplotlib_backend/backend_interagg.py
第一步:在文件顶部添加 import
python
import numpy as np
第二步:找到第 85 行左右的 show 方法
将原来的:
python
buffer = self.tostring_rgb()
替换为:
python
buffer = np.frombuffer(self.buffer_rgba(), dtype=np.uint8).reshape(-1, 4)[:, :3].tobytes()
保存文件,重启 PyCharm 即可。
为什么这样改?
| 原方法 | 说明 |
|---|---|
self.tostring_rgb() |
matplotlib 旧 API,返回 RGB 字节,3.9 后已删除 |
self.buffer_rgba() |
新 API,返回 RGBA 字节(4 通道) |
np.frombuffer(...).reshape(-1, 4)[:, :3] |
将 RGBA(4 通道)转为 RGB(3 通道),兼容 PyCharm 原有的图像解析逻辑 |
方法二:禁用 PyCharm 交互模式(临时方案)
Settings → 工具 → Python 图 → 取消勾选"使用交互模式"
这样 PyCharm 不会拦截 matplotlib 的输出,plt.show() 会以独立窗口弹出。但 Plots 工具窗口将无法使用。
验证修复
创建一个测试脚本:
python
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()
运行后确认:
- 右侧 Plots 工具窗口正常显示图表
- 图表内容清晰,无花屏/重叠
- 运行结束退出码为
0
注意事项
- PyCharm 升级版本后需要重新检查此文件,新版本可能已修复
- 此方法不影响项目中使用的 matplotlib 版本,无需降级
- 修改的是 PyCharm 的插件文件,不是项目代码
适用环境
| 项目 | 版本 |
|---|---|
| PyCharm | 2024.1.x Professional |
| matplotlib | >= 3.9 |
| Python | 3.x |
| OS | Windows / macOS / Linux |