使用Matplotlib与Numpy时遇AttributeError错误求助
解决Matplotlib导入时出现的
AttributeError: module 'numbers' has no attribute 'Integral'错误 问题重现
我正在学习使用Matplotlib,安装了Anaconda3和VSCode。Anaconda3已预装所需库,但运行一段简单代码时出现错误。
运行的代码
import matplotlib.pyplot as plt fig, ax = plt.subplots() fruits = ['apple', 'blueberry', 'cherry', 'orange'] counts = [40, 100, 30, 55] bar_labels = ['red', 'blue', '_red', 'orange'] bar_colors = ['tab:red', 'tab:blue', 'tab:red', 'tab:orange'] ax.bar(fruits, counts, label=bar_labels, color=bar_colors) ax.set_ylabel('fruit supply') ax.set_title('Fruit supply by kind and color') ax.legend(title='Fruit color') plt.show()
错误信息
Traceback (most recent call last): File "c:\Users\ahmed\Desktop\saved\mat1.py", line 1, in <module> import matplotlib.pyplot as plt File "C:\Users\ahmed\anaconda3\lib\site-packages\matplotlib\__init__.py", line 104, in <module> import numpy File "C:\Users\ahmed\anaconda3\lib\site-packages\numpy\__init__.py", line 150, in <module> from . import core File "C:\Users\ahmed\anaconda3\lib\site-packages\numpy\core\__init__.py", line 70, in <module> from . import numerictypes as nt File "C:\Users\ahmed\anaconda3\lib\site-packages\numpy\core\numerictypes.py", line 596, in <module> _register_types() File "C:\Users\ahmed\anaconda3\lib\site-packages\numpy\core\numerictypes.py", line 591, in _register_types numbers.Integral.register(integer) AttributeError: module 'numbers' has no attribute 'Integral'
解决方案
1. 检查并移除本地同名文件
- 查看代码所在目录(
c:\Users\ahmed\Desktop\saved\),如果存在名为numbers.py的文件,立即重命名(比如改成my_numbers.py) - 如果目录里有
numbers.pyc缓存文件,也一并删除 - 原因:本地的
numbers.py会覆盖Python标准库中的numbers模块,导致numpy无法找到Integral属性
2. 重新安装numpy和matplotlib修复损坏库
打开Anaconda Prompt,执行以下命令:
conda install --force-reinstall numpy matplotlib
该命令会强制重新安装numpy和matplotlib,修复可能损坏或版本不兼容的库文件
3. 确认VSCode使用Anaconda的Python解释器
- 打开VSCode,点击右下角显示的Python版本号,选择Anaconda安装目录下的Python解释器(路径类似
C:\Users\ahmed\anaconda3\python.exe) - 或者按
Ctrl+Shift+P,输入Python: Select Interpreter,在列表中选择Anaconda对应的解释器 - 原因:如果VSCode使用系统自带Python而非Anaconda的解释器,会导致库路径不匹配
内容的提问来源于stack exchange,提问作者AlwaysJona
相关产品推荐
相关产品推荐

