NameError:名称“matplotlib”未在 Python 中定义
NameError: name ‘matplotlib’ is not defined in Python
当我们使用matplotlib
模块而不先导入它时,会出现 Python“NameError: name ‘matplotlib’ is not defined”。要解决该错误,请安装模块并在使用前导入它。
在项目的根目录中打开终端并安装matplotlib
模块。
# 👇️ in a virtual environment or using Python 2 pip install matplotlib # 👇️ for python 3 (could also be pip3.10 depending on your version) pip3 install matplotlib # 👇️ if you get permissions error sudo pip3 install matplotlib # 👇️ if you don't have pip in your PATH environment variable python -m pip install matplotlib # 👇️ for python 3 (could also be pip3.10 depending on your version) python3 -m pip install matplotlib # 👇️ alternative for Ubuntu/Debian sudo apt-get install python3-matplotlib # 👇️ alternative for CentOS sudo yum install python3-matplotlib # 👇️ alternative for Fedora sudo yum install python3-matplotlib # 👇️ for Anaconda conda install -c conda-forge matplotlib
安装matplotlib模块后,确保在使用前导入它。
# ✅ import matplotlib.pyplot and alias it to plt import matplotlib.pyplot as plt # ✅ import matplotlib.image and alias it to pmimg import matplotlib.image as mpimg fig, ax = plt.subplots() print(fig) print(ax) img = mpimg.imread('../../doc/_static/stinkbug.png') print(img)
我们在从matplotlib
.
We imported matplotlib.pyplot
and aliased it to plt
, so you would access any
pyplot methods as plt.plot()
, plt.ylabel()
, plt.show()
, etc.
Make sure you haven’t misspelled the module you are importing because module
names are case-sensitive.
Also, make sure you haven’t imported from matplotlib
in a nested scope, e.g. a
function. Import the module at the top level to be able to use it throughout
your code.
Conclusion #
The Python “NameError: name ‘matplotlib’ is not defined” occurs when we use
the matplotlib
module without importing it first. To solve the error, install
the module and import it before using it.