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.
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
The ImportError: No module named matplotlib.pyplot occurs if you have not installed the Matplotlib library in Python and trying to run the script which has matplotlib related code. Another issue might be that you are not importing the matplotlib.pyplot properly in your Python code.
In this tutorial, let’s look at installing the matplotlib module correctly in different operating systems and solve No module named matplotlib.pyplot.
Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python.
Matplotlib is not a built-in module (it doesn’t come with the default python installation) in Python, you need to install it explicitly using the pip installer and then use it.
If you looking at how to install pip or if you are getting an error installing pip checkout pip: command not found to resolve the issue.
Matplotlib releases are available as wheel packages for macOS, Windows and Linux on PyPI. Install it using pip:
Install Matplotlib in OSX/Linux
The recommended way to install the matplotlib module is using pip or pip3 for Python3 if you have installed pip already.
Using Python 2
$ sudo pip install matplotlib
Using Python 3
$ sudo pip3 install matplotlib
Alternatively, if you have easy_install in your system, you can install matplotlib using the below command.
Using easy install
$ sudo easy_install -U matplotlib
For CentOs
$ yum install python-matplotlib
For Ubuntu
To install matplotlib module on Debian/Ubuntu :
$ sudo apt-get install python3-matplotlib
Install Matplotlib in Windows
In the case of windows, you can use pip or pip3 based on the Python version, you have to install the matplotlib module.
$ pip3 install matplotlib
If you have not added the pip to the environment variable path, you can run the below command in Python 3, which will install the matplotlib module.
$ py -m pip install matplotlib
Install Matplotlib in Anaconda
Matplotlib is available both via the anaconda main channel and it can be installed using the following command.
$ conda install matplotlib
You can also install it via the conda-forge community channel by running the below command.
$ conda install -c conda-forge matplotlib
In case you have installed it properly but it still throws an error, then you need to check the import statement in your code.
In order to plot the charts properly, you need to import the matplotlib as shown below.
# importing the matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
# car sales data
total_sales = [3000, 2245, 1235, 5330, 4200]
location = ['Bangalore', 'Delhi', 'Chennai', 'Mumbai', 'Kolkatta']
# Seaborn color palette to plot pie chart
colors = sns.color_palette('pastel')
# create pie chart using matplotlib
plt.pie(total_sales, labels=location, colors=colors)
plt.show()
Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.
Sign Up for Our Newsletters
Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.
By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.
I use Eclipse + Pydev to develop my python examples. But one day when I am coding a Matplotlib example in the Eclipse PyDev project, and when I run the example, I meet the following error messages. This article will tell you how to fix it.
1. ModuleNotFoundError: No Module Named ‘matplotlib.pyplot’; ‘matplotlib’ Is Not A Package.
- Below are the detailed error messages.
Traceback (most recent call last): File "D:Workdev2qa.com-example-codePythonExampleProjectcomdev2qaexamplecode_learner_dot_com_examplematplotlib.py", line 7, in <module> import matplotlib.pyplot as plt File "D:Workdev2qa.com-example-codePythonExampleProjectcomdev2qaexamplecode_learner_dot_com_examplematplotlib.py", line 7, in <module> import matplotlib.pyplot as plt ModuleNotFoundError: No module named 'matplotlib.pyplot'; 'matplotlib' is not a package
2.How To Fix ModuleNotFoundError: No Module Named ‘matplotlib.pyplot’; ‘matplotlib’ Is Not A Package.
- First, you should make sure the python Matplotlib module has been installed, you can refer to the article Python 3 Matplotlib Draw Point/Line Example section 1. Verify matplotlib Has Been Installed.
- Then you should confirm that you have added the Matplotlib library in your Eclipse PyDev project Python interpreter. You can refer to the article How To Add Library In Python Eclipse Project to learn more.
- But in my example, the error still exists. I finally find that the reason is that my example python file name is matplotlib.py, so when I run the example file, the imports code import matplotlib.pyplot as plt will import the pyplot class from the current example module file, but there does not have the pyplot class in the example module, so the error occurred.
- So I change the example python file name to matplotlib_example.py, then the error has been fixed.
- what a simple and silly error.
A common error you may encounter when using Python is modulenotfounderror: no module named ‘matplotlib’. This error occurs when Python cannot detect the Matplotlib library in your current environment. This tutorial goes through the exact steps to troubleshoot this error for the Windows, Mac and Linux operating systems.
Table of contents
- ModuleNotFoundError: no module named ‘matplotlib’
- What is ModuleNotFoundError?
- What is Matplotlib?
- How to Install Matplotlib on Windows Operating System
- How to Install Matplotlib on Mac Operating System
- How to Install Matplotlib on Linux Operating Systems
- Installing pip for Ubuntu, Debian, and Linux Mint
- Installing pip for CentOS 8 (and newer), Fedora, and Red Hat
- Installing pip for CentOS 6 and 7, and older versions of Red Hat
- Installing pip for Arch Linux and Manjaro
- Installing pip for OpenSUSE
- Check Matplotlib Version
- Installing Matplotlib Using Anaconda
- Importing matplotlib.pyplot
- Summary
ModuleNotFoundError: no module named ‘matplotlib’
What is ModuleNotFoundError?
The ModuleNotFoundError occurs when the module you want to use is not present in your Python environment. There are several causes of the modulenotfounderror:
The module’s name is incorrect, in which case you have to check the name of the module you tried to import. Let’s try to import the re module with a double e to see what happens:
import ree
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
1 import ree
ModuleNotFoundError: No module named 'ree'
To solve this error, ensure the module name is correct. Let’s look at the revised code:
import re
print(re.__version__)
2.2.1
You may want to import a local module file, but the module is not in the same directory. Let’s look at an example package with a script and a local module to import. Let’s look at the following steps to perform from your terminal:
mkdir example_package
cd example_package
mkdir folder_1
cd folder_1
vi module.py
Note that we use Vim to create the module.py file in this example. You can use your preferred file editor, such as Emacs or Atom. In module.py, we will import the re module and define a simple function that prints the re version:
import re
def print_re_version():
print(re.__version__)
Close the module.py, then complete the following commands from your terminal:
cd ../
vi script.py
Inside script.py, we will try to import the module we created.
import module
if __name__ == '__main__':
mod.print_re_version()
Let’s run python script.py from the terminal to see what happens:
Traceback (most recent call last):
File "script.py", line 1, in <module>
import module
ModuleNotFoundError: No module named 'module'
To solve this error, we need to point to the correct path to module.py, which is inside folder_1. Let’s look at the revised code:
import folder_1.module as mod
if __name__ == '__main__':
mod.print_re_version()
When we run python script.py, we will get the following result:
2.2.1
Lastly, you can encounter the modulenotfounderror when you import a module that is not installed in your Python environment.
What is Matplotlib?
Matplotlib is a data visualization and graphical plotting library for Python. Matplotlib is an open-source alternative to MATLAB. Pyplot is a Matplotlib module, which provides a MATLAB-like interface. You can use pyplot to create various plots, including line, histogram, scatter, 3D, image, contour, and polar.
The simplest way to install Matplotlib is to use the package manager for Python called pip. The following installation instructions are for the major Python version 3.
How to Install Matplotlib on Windows Operating System
First, you need to download and install Python on your PC. Ensure you select the install launcher for all users and Add Python to PATH checkboxes. The latter ensures the interpreter is in the execution path. Pip is automatically on Windows for Python versions 2.7.9+ and 3.4+.
You can check your Python version with the following command:
python3 --version
You can install pip on Windows by downloading the installation package, opening the command line and launching the installer. You can install pip via the CMD prompt by running the following command.
python get-pip.py
You may need to run the command prompt as administrator. Check whether the installation has been successful by typing.
pip --version
To install matplotlib with pip, run the following command from the command prompt.
pip3 install matplotlib
How to Install Matplotlib on Mac Operating System
Open a terminal by pressing command (⌘) + Space Bar to open the Spotlight search. Type in terminal and press enter. To get pip, first ensure you have installed Python3:
python3 --version
Python 3.8.8
Download pip by running the following curl command:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
The curl command allows you to specify a direct download link. Using the -o option sets the name of the downloaded file.
Install pip by running:
python3 get-pip.py
From the terminal, use pip3 to install Matplotlib:
pip3 install matplotlib
How to Install Matplotlib on Linux Operating Systems
All major Linux distributions have Python installed by default. However, you will need to install pip. You can install pip from the terminal, but the installation instructions depend on the Linux distribution you are using. You will need root privileges to install pip. Open a terminal and use the commands relevant to your Linux distribution to install pip.
Installing pip for Ubuntu, Debian, and Linux Mint
sudo apt install python-pip3
Installing pip for CentOS 8 (and newer), Fedora, and Red Hat
sudo dnf install python-pip3
Installing pip for CentOS 6 and 7, and older versions of Red Hat
sudo yum install epel-release
sudo yum install python-pip3
Installing pip for Arch Linux and Manjaro
sudo pacman -S python-pip
Installing pip for OpenSUSE
sudo zypper python3-pip
Once you have installed pip, you can install Matplotlib using:
pip3 install matplotlib
Check Matplotlib Version
Once you have successfully installed Matplotlib, you can use two methods to check the version of Matplotlib. First, you can use pip show from your terminal. Remember that the name of the package is Matplotlib.
pip show matplotlib
Name: matplotlib
Version: 3.3.4
Summary: Python plotting package
Home-page: https://matplotlib.org
Second, within your python program, you can import Matlotlib and then reference the __version__ attribute:
import matplotlib
print(matplotlib.__version__)
3.3.4
Installing Matplotlib Using Anaconda
Anaconda is a distribution of Python and R for scientific computing and data science. You can install Anaconda by going to the installation instructions. Once you have installed Anaconda, you can install Matplotlib using the following command:
conda install -c conda-forge matplotlib
Importing matplotlib.pyplot
You can import the Pyplot API to create plots using the following lines in your program
import matplotlib.pyplot as plt
It is common to abbreviate the pyplot import to plt.
Summary
Congratulations on reading to the end of this tutorial. The modulenotfounderror occurs if you misspell the module name, incorrectly point to the module path or do not have the module installed in your Python environment. If you do not have the module installed in your Python environment, you can use pip to install the package. However, you must ensure you have pip installed on your system. You can also install Anaconda on your system and use the conda install command to install Matplotlib.
Go to the online courses page on Python to learn more about Python for data science and machine learning.
Have fun and happy researching!
One error you may encounter when using matplotlib is:
AttributeError: module 'matplotlib' has no attribute 'plot'
This error typically occurs when you use the following code to import matplotlib:
import matplotlib as plt
Instead, you should use:
import matplotlib.pyplot as plt
The following example shows how to fix this error in practice.
How to Reproduce the Error
Suppose we attempt to create a line plot in matplotlib using the following code:
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'
We receive an error because we used the wrong line of code to import the matplotlib library.
How to Fix the Error
To fix this error, we simply need to use the correct code to import the matplotlib library:
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()

Notice that we’re able to create the line plot successfully without receiving any errors because we used the correct line of code to import the matplotlib library.
Additional Resources
The following tutorials explain how to fix other common errors in Python:
How to Fix: No module named matplotlib
How to Fix: No module named pandas
How to Fix: No module named numpy
