PyCharm中Matplotlib绘图失败问题求助
解决Matplotlib在PyCharm中绘图时的backend_interagg属性错误
问题重现
运行以下Matplotlib绘图代码时触发AttributeError:
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 100) y = np.sin(x) plt.plot(x, y) plt.show()
错误信息:
AttributeError: module 'backend_interagg' has no attribute 'FigureCanvas'. Did you mean: 'FigureCanvasAgg'
解决方案
- 临时指定可用后端
在代码开头强制切换到稳定的后端,比如TkAgg或Qt5Agg,直接修改代码:
import matplotlib matplotlib.use('TkAgg') # 若TkAgg不可用,尝试'Qt5Agg'或'Agg' import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 100) y = np.sin(x) plt.plot(x, y) plt.show()
- 修改Matplotlib全局配置
- 运行以下代码找到Matplotlib配置文件路径:
import matplotlib print(matplotlib.matplotlib_fname())
- 打开找到的
matplotlibrc文件,找到backend配置项,将其修改为:
backend: TkAgg
- 保存文件后重启PyCharm。
- 重装Matplotlib修复损坏文件
如果是安装文件损坏导致的问题,卸载后重新安装:
pip uninstall matplotlib -y pip install matplotlib
若使用conda环境,执行:
conda uninstall matplotlib -y conda install matplotlib
- 校验PyCharm解释器环境
确认PyCharm使用的Python解释器已正确安装Matplotlib:
- 打开
File > Settings > Project: [你的项目名] > Python Interpreter - 查看已安装包列表,若没有matplotlib,点击
+搜索并安装;若已存在,可尝试升级到最新稳定版。
内容的提问来源于stack exchange,提问作者Ryan Schultz
相关产品推荐
相关产品推荐

