You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu 22.04中matplotlib导入docstring失败问题求助

解决Ubuntu 22.04 LTS中matplotlib导入错误:ImportError: cannot import name 'docstring' from 'matplotlib'

问题成因

这个错误源于matplotlib与系统自带mpl_toolkits版本不兼容:

  • 你通过pip安装了较新版本的matplotlib(路径/usr/local/lib/python3.10/dist-packages),该版本已将matplotlib.docstring模块重命名为matplotlib._docstring。
  • 但Ubuntu 22.04系统自带的mpl_toolkits.mplot3d(路径/usr/lib/python3.10/dist-packages)是适配旧版matplotlib的,仍在尝试导入已被移除的docstring模块,从而触发报错。

排查步骤

  1. 确认matplotlib的安装信息:
    pip show matplotlib
    
    查看输出中的Location是否为/usr/local/lib/python3.10/dist-packages,Version是否为3.7.x及以上(该版本开始重命名docstring)。
  2. 确认系统mplot3d的路径:
    python -c "import mpl_toolkits.mplot3d; print(mpl_toolkits.mplot3d.__file__)"
    
    若输出为/usr/lib/python3.10/dist-packages/mpl_toolkits/mplot3d/__init__.py,说明该模块来自系统apt包,而非pip安装。

解决方法

方法一:升级mpl_toolkits至兼容版本(推荐)

用pip安装适配当前matplotlib版本的mpl_toolkits,覆盖系统自带的旧版本:

pip install --upgrade mpl_toolkits

安装完成后,mpl_toolkits会被放到/usr/local/lib路径,优先于系统路径加载,解决版本不匹配问题。

方法二:降级matplotlib至兼容系统模块的版本

如果不想替换系统包,可将matplotlib降级到3.6.x及以下版本(该版本仍保留matplotlib.docstring):

pip install matplotlib==3.6.3

此版本与Ubuntu 22.04自带的mplot3d完全兼容。

方法三:临时调整模块搜索优先级(应急方案)

仅用于临时测试,不建议长期使用:
通过设置PYTHONPATH让系统路径优先加载,覆盖pip安装的matplotlib:

PYTHONPATH=/usr/lib/python3.10/dist-packages:$PYTHONPATH python

进入Python交互环境后即可正常导入matplotlib.pyplot。

内容的提问来源于stack exchange,提问作者thor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 11:37:40