Nameerror: name ‘plt’ is not defined ( Quick Fix )

Data visualization is a must for every data scientist. There are many Python packages for it. Matplotlib is one of them. But while using this package you may encounter the error Nameerror: name ‘plt’ is not defined. In this post, you will know when this error comes and how to solve it easily.

What is NameError?

In most cases, the coder gets NameError when they forget to use the variable, function before defining them. You can also get the error when you forget to import the constructor from a particular package.

Why Nameerror: name ‘plt’ is not defined Error comes?

The root cause for getting this error is that you may not be using the plt alias. In most cases, coders use to import the pyplot module from the matplotlib library.

You will get the error when you will run the below lines of code.

import matplotlib.pyplot
fig, ax = plt.subplots()
print(fig)
print(ax)

Output

Nameerror name plt is not defined Error
Nameerror name plt is not defined Error

You can see in the above code you are getting the error as there is no mention of the plt in any line of code.

Solve name ‘plt’ is not defined Error

The solution to the above error is very simple. You have to properly import the matplotlib module with plt as an alias. Use the below line of code to import the pyplot as plt alias.

import matplotlib.pyplot as plt

Now you will run the below lines of code then you will not get the error.

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
print(fig)
print(ax)

Output

Nameerror name plt is not defined Error fix
Nameerror name plt is not defined Error fix

There can be also another cause for this error. You may not have installed the matplotlib packages in your system. To do so you have to use the below command in your terminal.

For python 3.xx

pip3 install matplotlib

For python 2.xx

pip install matplotlib

Conclusion

NameError is an error raised when the Python interpreter is unable to find the variable or function defined in the code. If you are getting the Nameerror: name ‘plt’ is not defined error then the above solution will solve it.

I hope you have found the solution for this error on our site. If you have any queries then you can contact us for more help.

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Meet Sukesh ( Chief Editor ), a passionate and skilled Python programmer with a deep fascination for data science, NumPy, and Pandas. His journey in the world of coding began as a curious explorer and has evolved into a seasoned data enthusiast.
 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner