NameError:名称“plt”未在 Python 中定义
NameError: name ‘plt’ is not defined in Python
Python“NameError: name ‘plt’ is not defined”发生在我们使用
pyplot
模块而不先导入它时。要解决该错误,请在使用前安装
matplotlib
并导入plt
( import matplotlib.pyplot as plt
)。
在项目的根目录中打开终端并安装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模块后,确保pyplot
在使用前导入它。
# 👇️ import pyplot and alias it as plt import matplotlib.pyplot as plt fig, ax = plt.subplots() print(fig) print(ax)
我们使用别名从as导入pyplot
模块。matplotlib
plt
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 placed your import statement 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 ‘plt’ is not defined” occurs when we use the
pyplot
module without importing it first. To solve the error, install
matplotlib
and import plt
(import matplotlib.pyplot as plt
) before using
it.