How to solve the name error: ‘plt’ is not defined in matplotlib and Python?

Fix nameerror plt is not defined in matplotlib

To solve this error make sure to import the Python Matplotlib package and assign it the alias plt before invoking any of the Matplotlib plotting methods in your notebook or script:

import matplotlib.pyplot as plt
#your code here
fig, ax = plt.subplots()

Understanding the name error plt not found

Assume that you have written the following snippet in your Jupyter Notebook:

import matplotlib.pyplot

fig, ax = plt.subplots()

x = [10,20, 30, 40, 50]
y = [15, 20, 30,40, 10]

ax.plot(x,y);

When invoking the code you will get the following exception:

The root cause for this error, is that your code is trying to invoke the matplotlib plot function before importing the pyplot module of the matplotlib package.

Fixing the nameerror for matplotlib in Python

In order to fix this error, you need to make sure to import the matplotlib package, and plt module. Before importing matplotlib, make sure that matplotlib is installed in your computer.

Here’s the code, note that in the first line we invoked matplotlib pyplot module and assign it the alias plt.

import matplotlib.pyplot as plt   #defines the plt alias for the pyplot module

fig, ax = plt.subplots()

x = [10,20, 30, 40, 50]
y = [15, 20, 30,40, 10]

ax.plot(x,y);

You could as well use the following code to import pyplot:

from matplotlib import pyplot as plt

Or without using an alias – not recommended, as it makes your code more cumbersome to write and to read:

import matplotlib.pyplot

fig, ax = matplotlib.pyplot.subplots()

x = [10,20, 30, 40, 50]
y = [15, 20, 30,40, 10]

ax.plot(x,y);

FAQ:

How to prevent name error exceptions in Python?

  • Use meaningful variable names and ensure proper use of variable scope.
  • Use conditional statements to handly variables which might not exist.
  • You can verify the existence of variable existence using the type() function.

I typically use VSCode and PyCharm for my Python development?

The instructions provided so far will work not only for JupyTer but for any Python IDE, such as Spyder, VS Code, Google Colab and others.