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

TL; DR : Fix nameerror plt is not defined in matplotlib

To solve this error make sure to import the Python matplotlib package and call the pyplot module into your Jupyter Notebook. Then 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);