解决 PyCharm 2024.1+ matplotlib 图表显示异常:Plots 工具窗口空白 / tostring_rgb 报错

解决 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
相关推荐
执明wa6 小时前
Android Studio 打包 APK
android·ide·android studio
好悬给我拽开线9 小时前
RoboTTT
ide·vscode·编辑器
2601_9622946111 小时前
Python工具软件开发:借助InsCode AI IDE开启智能编程新时代
ide·python·ai·开发工具·智能化编程
2601_962298931 天前
配置 Python 解释器
pycharm·wsl·虚拟环境·配置python解释器·远程解释器
心平气和量大福大1 天前
android studio(AS)工具-调试-统计总行数
android·ide·android studio
开开心心_Every2 天前
实现鼠标键盘动作录制与重复播放的工具
微信·jupyter·pycharm·pdf·计算机外设·word·excel
2601_962298932 天前
pycharm如何添加python解释器
pycharm·项目管理·虚拟环境·python解释器·设置步骤
2501_915106322 天前
第一次开发 iPhone App,可能碰到的问题,解决办法
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
OsDepK3 天前
xcode应用构建至testflight测试流程
ide·macos·xcode
frjc3 天前
如何在 IDEA 中打开并运行已有Java项目
java·ide·intellij-idea