How to Solve "NameError: name 'plt' is not defined" and "NameError: name 'matplotlib' is not defined" in Python
The errors NameError: name 'plt' is not defined
and NameError: name 'matplotlib' is not defined
in Python both indicate the same problem: you're trying to use the matplotlib
library (or its pyplot
module, commonly aliased as plt
) without importing it first.
This guide explains the cause of these errors and provides the correct solutions.
Understanding the NameError
Both of these NameError
messages mean that Python doesn't recognize the name plt
or matplotlib
. This happens because you haven't told Python where to find these names. In Python, you must explicitly import
modules and packages before you can use them. matplotlib
is a third-party library for plotting, and matplotlib.pyplot
(often imported as plt
) is a submodule that provides a convenient interface for creating plots.
Solution: Importing matplotlib.pyplot
The standard and recommended way to import matplotlib.pyplot
is:
import matplotlib.pyplot as plt # Import and alias as plt
fig, ax = plt.subplots() # Now you can use plt
print(fig)
print(ax)
import matplotlib.pyplot as plt
: This line does three things:import matplotlib.pyplot
: Imports thepyplot
module from thematplotlib
package.as plt
: Gives it the aliasplt
. This is a very common convention. Usingplt
is much shorter and more readable than typingmatplotlib.pyplot
everywhere.
- You can also use
from matplotlib import pyplot as plt
, which imports only thepyplot
module.
Common Import Mistakes to Avoid
Here are some common mistakes that can still lead to a NameError
even if you think you've imported matplotlib
:
Importing Inside a Function (Local Scope)
If you import matplotlib
inside a function, it's only available within that function's scope:
def example():
import matplotlib.pyplot as plt # BAD: Local import
fig, ax = plt.subplots()
print(fig)
print(ax)
# ⛔️ NameError: name 'plt' is not defined (outside the function)
# fig, ax = plt.subplots()
Solution: Always import modules at the top level of your script:
import matplotlib.pyplot as plt # GOOD: Top-level import
def example():
fig, ax = plt.subplots()
print(fig)
print(ax)
fig, ax = plt.subplots() # Works now
Importing Inside a try-except
Block
Avoid importing inside a try-except
block that might fail:
try:
# Code here could raise an error
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
print(fig)
print(ax)
except ImportError: # Exception is caught here
print("matplotlib is not found.")
# ⛔️ NameError: name 'plt' is not defined (if import failed)
#fig, ax = plt.subplots()
- The
plt
won't be accessible outside the try/except block.
Solution: Import at the top level, outside any try-except
blocks:
import matplotlib.pyplot as plt # Correct import
try:
fig, ax = plt.subplots()
print(fig)
print(ax)
except ImportError: # This is used in case of failure
print("matplotlib is not found.")
Typos and Case Sensitivity
Python is case-sensitive. plt
, matplotlib
, and pyplot
must be spelled and capitalized exactly as shown. Double-check for typos.
Shadowing the module
Don't name your files or variables with the same name as the library, otherwise the import will not work as expected.
Conclusion
The NameError: name 'plt' is not defined
and NameError: name 'matplotlib' is not defined
errors are easily fixed by correctly importing the matplotlib.pyplot
module (usually as plt
) at the top of your Python file.
Avoid importing inside functions or try-except
blocks.
By following these best practices, you can ensure that matplotlib
is available throughout your code. If you have the library installed and you are still getting this error, make sure you are using the correct Python interpreter (and virtual environment, if applicable).