Import matplotlib pyplot as plt ошибка

I am currently practicing matplotlib. This is the first example I practice.

#!/usr/bin/python

import matplotlib.pyplot as plt

radius = [1.0, 2.0, 3.0, 4.0]
area = [3.14159, 12.56636, 28.27431, 50.26544]

plt.plot(radius, area)
plt.show()

When I run this script with python ./plot_test.py, it shows plot correctly. However, I run it by itself, ./plot_test.py, it throws the followings:

Traceback (most recent call last):
  File "./plot_test.py", line 3, in <module>
    import matplotlib.pyplot as plt
ImportError: No module named matplotlib.pyplot

Does python look for matplotlib in different locations?

The environment is:

  • Mac OS X 10.8.4 64bit
  • built-in python 2.7

numpy, scipy, matplotlib is installed with:

sudo port install py27-numpy py27-scipy py27-matplotlib 
py27-ipython +notebook py27-pandas py27-sympy py27-nose

I did not have any problem to use «plt», but it suddenly shows an error message and does not work, when I import it. Please see the below.

>>> import matplotlib
>>> import matplotlib.pyplot as plt

Output:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/site-packages/matplotlib/pyplot.py", line 6, in <module>
    from matplotlib.figure import Figure, figaspect
 File "/usr/lib64/python2.6/site-packages/matplotlib/figure.py", line 18, in <module>
   from axes import Axes, SubplotBase, subplot_class_factory
 File "/usr/lib64/python2.6/site-packages/matplotlib/axes.py", line 2, in <module>
   import math, sys, warnings, datetime, new
 File "new.py", line 12, in <module>
   import matplotlib.pyplot as plt
 AttributeError: 'module' object has no attribute 'pyplot'

This package is suddenly corrupted. So, I tried to install as below. I use Ubuntu.

In [1]: sudo apt-get install python-matplotlib
  File "<ipython-input-1-2400ac877ebd>", line 1
    sudo apt-get install python-matplotlib
   ^
SyntaxError: invalid syntax

If I need to reinstall, what are the detailed instructions on how to do it?

I am very new to Python. So, my problem might be too simple to be solved. But I cannot.

This error typically occurs when you try to use the state-based interface to Matplotlib called matplotlib.pyplot but do not define the alias plt when importing the API. You can solve this error by using the as keyword to alias the matplotlib.pyplot API, for example:

import matplotlib.pyplot as plt

This tutorial will go through how to solve this error with code examples.


Table of contents

  • NameError: name ‘plt’ is not defined
  • Example
    • Solution #1: Use the as keyword
    • Solution #2: Do not use aliasing
    • Solution #3: Use the from keyword
  • Summary

NameError: name ‘plt’ is not defined

Python raises the NameError when it cannot recognise a name in our program. In other words, the name we are trying to use is not defined in the local or global scope. A name can be related to a built-in function, module, or something we define in our programs, like a variable or a function.

The error typically arises when:

  • We misspell a name
  • We do not define a variable or function
  • We do not import a module

In this tutorial, the source of the error NameError: name ‘plt’ is not defined is due to either not aliasing or incorrectly aliasing the numpy module. Let’s look at an example.

Example

Let’s look at an example of plotting a two-dimensional heatmap using NumPy and matplotlib. First, we must have numpy and matplotlib installed. You can go to the following article to learn how to install numpy and matplotlib for your operating system:

  • How to Solve Python ModuleNotFoundError: no module named ‘numpy’.
  • How to Solve Python ModuleNotFoundError: no module named ‘matplotlib’

The API pyplot provides a collection of functions for plot manipulation like MATLAB. We can access the pyplot API through the matplotlib module using matplotlib.pyplot.

import numpy as np
import matplotlib.pyplot

# Generate some test data
x = np.random.randn(8873)
y = np.random.randn(8873)

heatmap, xedges, yedges = np.histogram2d(x, y, bins=50)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

plt.clf()
plt.imshow(heatmap.T, extent=extent, origin='lower')
plt.show()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [1], in <cell line: 11>()
      8 heatmap, xedges, yedges = np.histogram2d(x, y, bins=50)
      9 extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
---> 11 plt.clf()
     12 plt.imshow(heatmap.T, extent=extent, origin='lower')
     13 plt.show()

NameError: name 'plt' is not defined

The error occurs because we installed matplotlib.pyplot but did not correctly alias the module as plt. Therefore, the name plt is not defined, and we cannot create and show the plot.

Solution #1: Use the as keyword

The easiest way to solve this error is to use the as keyword to create the alias plt. Let’s look at the updated code:

import numpy as np
import matplotlib.pyplot as plt

# Generate some test data
x = np.random.randn(8873)
y = np.random.randn(8873)

heatmap, xedges, yedges = np.histogram2d(x, y, bins=50)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

plt.clf()
plt.imshow(heatmap.T, extent=extent, origin='lower')
plt.show()

Let’s run the code to get the heatmap:

2D Heatmap of random numbers using pyplot

2D Heatmap of random numbers using pyplot

Solution #2: Do not use aliasing

We can also solve this error by removing the alias and using the module’s full name. Let’s look at the revised code:

import numpy as np
import matplotlib.pyplot 

# Generate some test data
x = np.random.randn(8873)
y = np.random.randn(8873)

heatmap, xedges, yedges = np.histogram2d(x, y, bins=50)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

matplotlib.pyplot.clf()
matplotlib.pyplot.imshow(heatmap.T, extent=extent, origin='lower')
matplotlib.pyplot.show()

Let’s run the code to get the heatmap:

2D Heatmap of random numbers using pyplot

2D Heatmap of random numbers using pyplot

This approach involves duplicate code and can make code less readable. Aliasing is a more concise way of writing code.

Solution #3: Use the from keyword

We can also use the from keyword to import a specific variable, class, or function from a module. In this case, we want to import the clf, imshow and show functions from the pyplot API. Using the from keyword means we do not have to specify the API in the rest of the program. Let’s look at the revised code:

import numpy as np
from matplotlib.pyplot import clf, imshow, show
# Generate some test data
x = np.random.randn(8873)
y = np.random.randn(8873)

heatmap, xedges, yedges = np.histogram2d(x, y, bins=50)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

clf()
imshow(heatmap.T, extent=extent, origin='lower')
show()

Let’s run the code to get the heatmap:

2D Heatmap of random numbers using pyplot

2D Heatmap of random numbers using pyplot

We can also use the from keyword to import the pyplot API from matplotlib and then alias it using the as keyword. Let’s look at the updated code:

import numpy as np
from matplotlib import pyplot as plt

# Generate some test data
x = np.random.randn(8873)
y = np.random.randn(8873)

heatmap, xedges, yedges = np.histogram2d(x, y, bins=50)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

plt.clf()
plt.imshow(heatmap.T, extent=extent, origin='lower')
plt.show()

Let’s run the code to get the heatmap.

2D Heatmap of random numbers using pyplot

2D Heatmap of random numbers using pyplot

The import statement from matplotlib import pyplot as plt is equivalent to import matplotlib.pyplot as plt. The latter import statement is preferred among Python developers as it is more concise and readable

Summary

Congratulations on reading to the end of this tutorial.

For further reading on errors involving NameErrors, go to the articles:

  • How to Solve Python NameError: name ‘xrange’ is not defined
  • How to Solve Python NameError: name ‘os’ is not defined
  • How to Solve Python NameError: name ‘pd’ is not defined

Go to the online courses page on Python to learn more about Python for data science and machine learning.

Have fun and happy researching!

Hello,

I’m trying to run the CNTK tutorial notebook: CNTK_101_LogisticRegression.
I cannot import matplotlib.pyplot

(base) C:CNTK-Samples-2-3-1Tutorials>python
Python 3.6.3 |Anaconda custom (64-bit)| (default, Oct 15 2017, 03:27:45) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib
>>> import matplotlib.pyplot as plt
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:UsersCharlesAnaconda3libsite-packagesmatplotlibpyplot.py", line 32, in <module>
    import matplotlib.colorbar
  File "C:UsersCharlesAnaconda3libsite-packagesmatplotlibcolorbar.py", line 36, in <module>
    import matplotlib.contour as contour
  File "C:UsersCharlesAnaconda3libsite-packagesmatplotlibcontour.py", line 21, in <module>
    import matplotlib.font_manager as font_manager
  File "C:UsersCharlesAnaconda3libsite-packagesmatplotlibfont_manager.py", line 58, in <module>
    from matplotlib import afm, cbook, ft2font, rcParams, get_cachedir
ImportError: DLL load failed: The specified procedure could not be found.
>>> quit()

(base) C:CNTK-Samples-2-3-1Tutorials>conda install matplotlib
Solving environment: done

# All requested packages already installed.

(base) C:CNTK-Samples-2-3-1Tutorials>python
Python 3.6.3 |Anaconda custom (64-bit)| (default, Oct 15 2017, 03:27:45) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib.pyplot as plt
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:UsersCharlesAnaconda3libsite-packagesmatplotlibpyplot.py", line 32, in <module>
    import matplotlib.colorbar
  File "C:UsersCharlesAnaconda3libsite-packagesmatplotlibcolorbar.py", line 36, in <module>
    import matplotlib.contour as contour
  File "C:UsersCharlesAnaconda3libsite-packagesmatplotlibcontour.py", line 21, in <module>
    import matplotlib.font_manager as font_manager
  File "C:UsersCharlesAnaconda3libsite-packagesmatplotlibfont_manager.py", line 58, in <module>
    from matplotlib import afm, cbook, ft2font, rcParams, get_cachedir
ImportError: DLL load failed: The specified procedure could not be found.

>>> import matplotlib
>>> matplotlib.__file__
'C:\Users\Charles\Anaconda3\lib\site-packages\matplotlib\__init__.py'
>>> print(matplotlib.__version__)
2.1.1

Any help will be greatly appreciated.

Charles

  • Редакция Кодкампа

17 авг. 2022 г.
читать 1 мин


Одна ошибка, с которой вы можете столкнуться при использовании matplotlib :

AttributeError : module 'matplotlib' has no attribute 'plot'

Эта ошибка обычно возникает, когда вы используете следующий код для импорта matplotlib:

import matplotlib as plt

Вместо этого вы должны использовать:

import matplotlib.pyplot as plt

В следующем примере показано, как исправить эту ошибку на практике.

Как воспроизвести ошибку

Предположим, мы пытаемся создать линейный график в matplotlib, используя следующий код:

import matplotlib as plt

#define data
x = [1, 2, 3, 4, 5, 6]
y = [3, 7, 14, 19, 15, 11]

#create line plot
plt.plot (x, y)

#show line plot
plt.show()

AttributeError : module 'matplotlib' has no attribute 'plot'

Мы получаем сообщение об ошибке, потому что мы использовали неправильную строку кода для импорта библиотеки matplotlib.

Как исправить ошибку

Чтобы исправить эту ошибку, нам просто нужно использовать правильный код для импорта библиотеки matplotlib:

import matplotlib.pyplot as plt

#define data
x = [1, 2, 3, 4, 5, 6]
y = [3, 7, 14, 19, 15, 11]

#create line plot
plt.plot (x, y)

#show line plot
plt.show() 

Обратите внимание, что мы можем успешно создать линейный график без каких-либо ошибок, потому что мы использовали правильную строку кода для импорта библиотеки matplotlib.

Дополнительные ресурсы

В следующих руководствах объясняется, как исправить другие распространенные ошибки в Python:

Как исправить: нет модуля с именем matplotlib
Как исправить: нет модуля с именем pandas
Как исправить: нет модуля с именем numpy

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Immergas ошибка е38
  • Immergas ошибка е10 как исправить
  • Immergas ошибка е02
  • Immergas ошибка e98

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии