PyCharm中使用Matplotlib报错:不存在'FigureCanvas'属性
Matplotlib 循环导入错误的排查与修复
代码示例
import matplotlib.pyplot as p1lt #define data x = [1, 2, 3, 4, 5, 6] y = [3, 7, 14, 19, 15, 11] #create line plot p1lt.plot(x, y) #show line plot p1lt.show()
运行报错
Matplotlib support failed Traceback (most recent call last): File "C:\Users\G\AppData\Roaming\JetBrains\IdeaIC2022.2\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 25, in do_import succeeded = activate_func() File "C:\Users\G\AppData\Roaming\JetBrains\IdeaIC2022.2\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_code_executor.py", line 29, in <lambda> "matplotlib": lambda: activate_matplotlib(self.enableGui), File "C:\Users\G\AppData\Roaming\JetBrains\IdeaIC2022.2\plugins\python-ce\helpers\pydev\pydev_ipython\matplotlibtools.py", line 110, in activate_matplotlib gui, backend = find_gui_and_backend() File "C:\Users\G\AppData\Roaming\JetBrains\IdeaIC2022.2\plugins\python-ce\helpers\pydev\pydev_ipython\matplotlibtools.py", line 47, in find_gui_and_backend backend = matplotlib.rcParams['backend'] File "D:\books\programming\python17\lib\site-packages\matplotlib\__init__.py", line 677, in __getitem__ plt.switch_backend(rcsetup._auto_backend_sentinel) File "D:\books\programming\python17\lib\site-packages\matplotlib\pyplot.py", line 251, in switch_backend switch_backend(candidate) File "D:\books\programming\python17\lib\site-packages\matplotlib\pyplot.py", line 266, in switch_backend canvas_class = backend_mod.FigureCanvas AttributeError: partially initialized module 'matplotlib.backends.backend_macosx' has no attribute 'FigureCanvas' (most likely due to a circular import) Process finished with exit code 0
问题背景
此前使用过Matplotlib,卸载重装Python和IntelliJ后出现上述错误,需排查问题原因并解决。
问题原因与修复方案
原因分析
错误提示指向backend_macosx模块的循环导入,结合卸载重装操作,核心原因包括:
- 卸载Python时未清理Matplotlib的残留配置文件,导致重装后加载了旧的后端配置;
- 系统为Windows,但Matplotlib自动选择了仅适用于Mac的
macosx后端; - 重装过程中Matplotlib安装不完整,部分模块损坏。
修复步骤
彻底清理Matplotlib残留
- 打开命令提示符,执行卸载命令:
pip uninstall -y matplotlib - 手动删除Windows下的Matplotlib配置目录:
C:\Users\G\.matplotlib
- 打开命令提示符,执行卸载命令:
重新安装Matplotlib
- 执行强制重装命令:
pip install matplotlib --force-reinstall - 国内用户可使用镜像源加速:
pip install matplotlib --force-reinstall -i https://pypi.tuna.tsinghua.edu.cn/simple
- 执行强制重装命令:
手动指定兼容后端
若重装后仍报错,在代码开头添加后端指定语句(Windows兼容的TkAgg或Qt5Agg):import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5, 6] y = [3, 7, 14, 19, 15, 11] plt.plot(x, y) plt.show()验证IntelliJ解释器配置
- 进入
File > Settings > Project: [项目名] > Python Interpreter; - 确认选中的解释器为重装后的Python版本,且Matplotlib已出现在已安装包列表中;
- 若存在多Python环境,确保项目绑定的是正确环境。
- 进入
内容的提问来源于stack exchange,提问作者Gaff
相关产品推荐
相关产品推荐

