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

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Raychan

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

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.

nameerror name matplotlib 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 it before using it.

main.py
# ✅ 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)

We used aliases when importing from 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.

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