Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Raychan
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.
Open your terminal in your project's root directory and install the matplotlib
module.
# 👇️ 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
After you install the matplotlib module,
make sure to import pyplot
before using it.
# 👇️ import pyplot and alias it as plt import matplotlib.pyplot as plt fig, ax = plt.subplots() print(fig) print(ax)
We used an alias to import the pyplot
module from matplotlib
as 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.