Fix - NameError: name 'plt' is not defined in Python

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Raychan

Fix - NameError: name 'plt' is not defined in Python #

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.

nameerror name plt is not defined

Open your terminal in your project's root directory and install the matplotlib module.

shell
# 👇️ 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.

main.py
# 👇️ 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.