No module named matplotlib как исправить ошибку

Одна распространенная ошибка, с которой вы можете столкнуться при использовании Python: no module named ' matplotlib ' Эта ошибка возникает, когда Python не обнаруживает библиотеку matplotlib в вашей текущей среде. В этом руководстве представлены точные шаги, которые вы можете использовать для устранения этой ошибки. Шаг 1: pip устанавливает matplotlib Поскольку matplotlib не устанавливается автоматически вместе с Python, вам нужно будет установить его самостоятельно. Самый простой способ
  • Редакция Кодкампа

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


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

no module named ' matplotlib '

Эта ошибка возникает, когда Python не обнаруживает библиотеку matplotlib в вашей текущей среде.

В этом руководстве представлены точные шаги, которые вы можете использовать для устранения этой ошибки.

Шаг 1: pip устанавливает matplotlib

Поскольку matplotlib не устанавливается автоматически вместе с Python, вам нужно будет установить его самостоятельно. Самый простой способ сделать это — использовать pip , менеджер пакетов для Python.

Вы можете запустить следующую команду pip для установки matplotlib:

pip install matplotlib

В большинстве случаев это исправит ошибку.

Шаг 2: Установите пип

Если вы все еще получаете сообщение об ошибке, вам может потребоваться установить pip. Используйте эти шаги , чтобы сделать это.

Вы также можете использовать эти шаги для обновления pip до последней версии, чтобы убедиться, что он работает.

Затем вы можете запустить ту же команду pip, что и раньше, чтобы установить matplotlib:

pip install matplotlib

На этом этапе ошибка должна быть устранена.

Шаг 3: проверьте версии matplotlib и pip

Если вы все еще сталкиваетесь с ошибками, возможно, вы используете другую версию matplotlib и pip.

Вы можете использовать следующие команды, чтобы проверить, совпадают ли ваши версии matplotlib и pip:

which python
python --version
which pip

Если две версии не совпадают, вам нужно либо установить более старую версию matplotlib, либо обновить версию Python.

Шаг 4: Проверьте версию matplotlib

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

pip show matplotlib

Name: matplotlib
Version: 3.1.3
Summary: Python plotting package
Home-page: https://matplotlib.org
Author: John D. Hunter, Michael Droettboom
Author-email: matplotlib-users@python.org
License: PSF
Location: /srv/conda/envs/notebook/lib/python3.7/site-packages
Requires: cycler, numpy, kiwisolver, python-dateutil, pyparsing
Required-by: seaborn, scikit-image
Note: you may need to restart the kernel to use updated packages.

Примечание. Самый простой способ избежать ошибок с версиями matplotlib и Python — просто установить Anaconda , набор инструментов, предустановленный вместе с Python и matplotlib и бесплатный для использования.

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

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

Как исправить: нет модуля с именем numpy
Как исправить: нет модуля с именем plotly
Как исправить: имя NameError ‘pd’ не определено
Как исправить: имя NameError ‘np’ не определено

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()

Avatar Of Srinivas Ramakrishna

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.

In this Python tutorial, we will discuss the modulenotfounderror: no module named ‘matplotlib’  and we shall also cover the following topics:

  • modulenotfounderror: no module named matplotlib windows 10
  • modulenotfounderror: no module named ‘matplotlib’ ubuntu
  • modulenotfounderror no module named ‘matplotlib’ python 3
  • modulenotfounderror no module named ‘matplotlib’ jupyter notebook
  • modulenotfounderror no module named ‘matplotlib’ anaconda
  • modulenotfounderror: no module named ‘matplotlib’ pycharm
  • modulenotfounderror: no module named ‘matplotlib.pyplot’; ‘matplotlib’ is not a package

Check if you have pip installed already, simply by writing pip in the python console. If you don’t have pip, get a python script called get-pip.py from the internet and save it to your local system. pip is the python package installer.

Take note of where the file got saved and change the current directory to that directory from the command prompt.

pip  -- Press Enter

-- If you don't have a pip then

cd path_of_directory_of_get-pip_script

Run the get-pip.py script to install pip by writing the following code in cmd (command prompt) to install pip:

"python .get-pip.py"

Now in cmd type the following code to install matplotlib with its dependencies:

pip install matplotlib

The error will be resolved, if not then follow through the end of this post.

Read: What is Matplotlib

modulenotfounderror: no module named ‘matplotlib’ ubuntu

If you don’t have matplotlib installed then to install Matplotlib for Python 3 through the APT package manager, you need the package python3-matplotlib:

sudo apt-get install python3-matplotlib

If you want to install it with pip for python 2.7, you need to use pip:

sudo pip install matplotlib

If the error still arises, follow through to the end of the post.

Read: How to install matplotlib

modulenotfounderror no module named ‘matplotlib’ python 3

You can install matplotlib with pip for python 3 and above, you just need to use pip3.

Open the python console and execute the command given below:

sudo pip3 install matplotlib

By executing the above code, the matplotlib for your python will be installed.

modulenotfounderror no module named ‘matplotlib’ jupyter notebook

Create a virtual environment inside your project directory. If you don’t have it, you have to install virtualenv by executing the following command in the cmd/terminal.

virtualenv environment_name   -- environment_name specifies the name of 
                              -- the environment variable created

Install matplotlib inside of your virtual environment.

pip3 install matplotlib

Now, install ipykernel inside your virtual environment.

pip3 install ipykernel

Connect your jupyter kernel to your new environment.

sudo python3 -m ipykernel install

When you start your jupyter notebook, you will see the option to select an environment, select the environment you have created which has matplotlib installed. Now, you are good to go with it.

Read: What is a Python Dictionary 

modulenotfounderror no module named ‘matplotlib’ anaconda

If you have Python installed previously, before installing Anaconda, the reason could be that it’s running your default Python installation instead of the one installed with Anaconda. You have to try prepending this to the top of your script:

#!/usr/bin/env python

If that does not work, restart the terminal and try installing matplotlib with conda in conda prompt or cmd, and see if it works.

conda install matplotlib

If the problem still not resolves, maybe you have to create a virtual environment as given in the above topics.

modulenotfounderror: no module named ‘matplotlib’ pycharm

You can get this error if you are using pycharm and have matplotlib.py in your current working directory. You have to just delete or rename the matplotlib.py file to resolve the issue, most probably it will work.

modulenotfounderror: no module named ‘matplotlib.pyplot’; ‘matplotlib’ is not a package

The error is caused because of the following reasons, check them out:

  • Make sure that the version of matplotlib you are installing is compaitible with your python version installed.
  • If the python installed is 64 bits version with matplotlib is 32bits. Make sure they are the same.
  • Make sure to add PATH variable for system and environment variables with path to the python.
  • If pip version is outdated, upgrade it to the latest version.
python -m pip install
  • Also make sure that there is no typos in the import statement.
  • If the error still exist then, try to check if there is any file matplotlib.py in your working directory. Remove that file, restart the kernel and import matplotib again. That should work.

You may also like reading the following articles.

  • How to install Django
  • Python Django vs Flask
  • Python NumPy shape
  • module ‘matplotlib’ has no attribute ‘plot’

In this Python tutorial, we have discussed the modulenotfounderror: no module named ‘matplotlib’ and we have also covered the following topics:

  • modulenotfounderror: no module named matplotlib windows 10
  • modulenotfounderror: no module named ‘matplotlib’ ubuntu
  • modulenotfounderror no module named ‘matplotlib’ python 3
  • modulenotfounderror no module named ‘matplotlib’ jupyter notebook
  • modulenotfounderror no module named ‘matplotlib’ anaconda
  • modulenotfounderror: no module named ‘matplotlib’ pycharm
  • modulenotfounderror: no module named ‘matplotlib.pyplot’; ‘matplotlib’ is not a package

Bijay Kumar MVP

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

No module named matplotlib error comes because either matplotlib is not installed or its path is not set properly. We can reinstall it to fix it. Sometimes we need to uninstall the older version if that is causing this Modulenotfounderror.  In this article, We will see many ways of installing it.

As we have already mentioned that we need to install/ reinstall matplotlib. Here we will mention a few different methods. Let’s see one by one.

Method 1: Installing matplotlib using pip –

pip package manager is one the easiest way for installing any python package. You may use the below command for installing matplotlib.

pip install matplotlib

no module name matplotlib

no module named matplotlib

Please ignore “!” before pip if you are running at local. It is specific to the collab notebook. For your local system, It works the same as we have mentioned.

In some scenarios, Like with the python 3. x version, You may alter the command-

python3 -m pip install matplotlib

Note –

1. If you have still an issue with the existing/older version of matplotlib. You may uninstall matplotlib. Here is the command for this.

pip uninstall matplotlib

It will remove the older version which is causing the issue of “no module named matplotlib”.

2. In some scenarios, We do not have pip install on the system. In that case, We need to install the pip manager first.

python -m pip install -U pip
python -m pip install -U matplotlib

This will install pip package. On top of it, It will install the matplotlib package for you.

Method 2: Matplotlib Installation using Conda Manager –

Similar to pip, We have another option as conda manager. Open the Anaconda Prompt and use the below command.

conda install matplotlib

Another way is to go with the conda-forge.

conda install -c conda-forge matplotlib

Conclusion –

I hope now you may easily resolve the bug no module named matplotlib. Still, if you are stuck with it. Please let us know. Your many comments below in the comment box.

Thanks
Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

We respect your privacy and take protecting it seriously

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

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!

In today’s post i would like to provide some troubleshooting information for people installing the matplotlib library package in their computers.

ModuleNotFoundError: no module named ‘matplotlib’ pyplot

This error is thrown when Python can’t find the Matplotlib package in your development environment. Most probably you’ll be able to troubleshoot this error by downloading the library from the Python repository using the PIP utility.

Install matplotlib with pip

In order to troubleshoot this error follow this process (explained for Windows, might require minor adjustments for MAC and Linux). Note that the process is identical for most Python add on libraries / packages such as Seaborn, NumPy, Pandas and many others.

  • Save your work, and close your Jupyter Notebooks/Lab, Spyder or other development environment you might be using.
  • Open your Command Prompt.
  • Type cmd.
  • Then in the command prompt type, type the following command:
pip install matplotlib
  • Now, go ahead and hit Enter.
  • Python will download the latest version of the matplotlib library from the Python package repository.
  • Once done, open your development environment and import matplotlib.
  • That’s it!

Anaconda environments

If you are have installed Anaconda, then by default, the basic Data Analysis packages, including Pandas and Matplotlib are already installed in your base environment. If for some reason you still receive an import error proceed as following.

  • From the Start mane, open Anaconda Navigator.
  • On the left hand side, hit the Environments tab (step 1)
  • Then highlight your Anaconda environment (step 2).
  • Then in the dropdown box (step 3), select Not Installed.
  • In the Search box, type matplotlib and hit Enter.
  • Then check the box near the package and hit Apply.
  • Then in the Install Packages dialog, click Apply again.
  • Once Anaconda Navigator is done, close it and reopen your development environment and download matplotlib.

Note: for completeness, you can also update your Anaconda environment manually (this is specially useful if you use MiniConda.

  • From the Windows Start Menu open the Anaconda Prompt
  • Type the following command
conda activate <path_to_your_environment>
  • Hit Enter.
  • Now type
conda install matplotlib
  • Hit Enter.
  • Matplotlib will be downloaded and installed.
  • That’s it.

Importerror no module named matplotlib.pyplot / matplotlib.path

This error is the base class of the ModuleNotFound error, and available since Python 3.3. The troubleshooting process we just described will remedy this error as well.

Questions? Feel free to leave us a comment

Ezoic

Содержание

  1. Как исправить: нет модуля с именем matplotlib
  2. Шаг 1: pip устанавливает matplotlib
  3. Шаг 2: Установите пип
  4. Шаг 3: проверьте версии matplotlib и pip
  5. Шаг 4: Проверьте версию matplotlib
  6. Дополнительные ресурсы
  7. Troubleshooting#
  8. Obtaining Matplotlib version#
  9. matplotlib install location#
  10. matplotlib configuration and cache directory locations#
  11. Getting help#
  12. Problems with recent git versions#
  13. How to fix Matplotlib modulenotfound import errors?
  14. ModuleNotFoundError: no module named ‘matplotlib’ pyplot
  15. Install matplotlib with pip
  16. Anaconda environments
  17. Importerror no module named matplotlib.pyplot / matplotlib.path
  18. [Solved] ImportError: No module named matplotlib.pyplot
  19. ImportError: No module named matplotlib.pyplot
  20. Install Matplotlib in OSX/Linux
  21. Install Matplotlib in Windows
  22. Install Matplotlib in Anaconda
  23. modulenotfounderror: no module named ‘matplotlib’
  24. modulenotfounderror: no module named matplotlib windows 10
  25. modulenotfounderror: no module named ‘matplotlib’ ubuntu
  26. modulenotfounderror no module named ‘matplotlib’ python 3
  27. modulenotfounderror no module named ‘matplotlib’ jupyter notebook
  28. modulenotfounderror no module named ‘matplotlib’ anaconda
  29. modulenotfounderror: no module named ‘matplotlib’ pycharm
  30. modulenotfounderror: no module named ‘matplotlib.pyplot’; ‘matplotlib’ is not a package

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

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

Эта ошибка возникает, когда Python не обнаруживает библиотеку matplotlib в вашей текущей среде.

В этом руководстве представлены точные шаги, которые вы можете использовать для устранения этой ошибки.

Шаг 1: pip устанавливает matplotlib

Поскольку matplotlib не устанавливается автоматически вместе с Python, вам нужно будет установить его самостоятельно. Самый простой способ сделать это — использовать pip , менеджер пакетов для Python.

Вы можете запустить следующую команду pip для установки matplotlib:

В большинстве случаев это исправит ошибку.

Шаг 2: Установите пип

Если вы все еще получаете сообщение об ошибке, вам может потребоваться установить pip. Используйте эти шаги , чтобы сделать это.

Вы также можете использовать эти шаги для обновления pip до последней версии, чтобы убедиться, что он работает.

Затем вы можете запустить ту же команду pip, что и раньше, чтобы установить matplotlib:

На этом этапе ошибка должна быть устранена.

Шаг 3: проверьте версии matplotlib и pip

Если вы все еще сталкиваетесь с ошибками, возможно, вы используете другую версию matplotlib и pip.

Вы можете использовать следующие команды, чтобы проверить, совпадают ли ваши версии matplotlib и pip:

Если две версии не совпадают, вам нужно либо установить более старую версию matplotlib, либо обновить версию Python.

Шаг 4: Проверьте версию matplotlib

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

Примечание. Самый простой способ избежать ошибок с версиями matplotlib и Python — просто установить Anaconda , набор инструментов, предустановленный вместе с Python и matplotlib и бесплатный для использования.

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

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

Источник

Troubleshooting#

Obtaining Matplotlib version#

To find out your Matplotlib version number, import it and print the __version__ attribute:

matplotlib install location#

You can find what directory Matplotlib is installed in by importing it and printing the __file__ attribute:

matplotlib configuration and cache directory locations#

Each user has a Matplotlib configuration directory which may contain a matplotlibrc file. To locate your matplotlib/ configuration directory, use matplotlib.get_configdir() :

On Unix-like systems, this directory is generally located in your HOME directory under the .config/ directory.

In addition, users have a cache directory. On Unix-like systems, this is separate from the configuration directory by default. To locate your .cache/ directory, use matplotlib.get_cachedir() :

On Windows, both the config directory and the cache directory are the same and are in your Documents and Settings or Users directory by default:

If you would like to use a different configuration directory, you can do so by specifying the location in your MPLCONFIGDIR environment variable — see Setting environment variables in Linux and macOS . Note that MPLCONFIGDIR sets the location of both the configuration directory and the cache directory.

Getting help#

There are a number of good resources for getting help with Matplotlib. There is a good chance your question has already been asked:

Stackoverflow questions tagged matplotlib.

If you are unable to find an answer to your question through search, please provide the following information in your e-mail to the mailing list:

Your operating system (Linux/Unix users: post the output of uname -a ).

Where you obtained Matplotlib (e.g., your Linux distribution’s packages, GitHub, PyPI, or Anaconda).

If the problem is reproducible, please try to provide a minimal, standalone Python script that demonstrates the problem. This is the critical step. If you can’t post a piece of code that we can run and reproduce your error, the chances of getting help are significantly diminished. Very often, the mere act of trying to minimize your code to the smallest bit that produces the error will help you find a bug in your code that is causing the problem.

Matplotlib provides debugging information through the logging library, and a helper function to set the logging level: one can call

to obtain this debugging information.

Standard functions from the logging module are also applicable; e.g. one could call logging.basicConfig(level=»DEBUG») even before importing Matplotlib (this is in particular necessary to get the logging info emitted during Matplotlib’s import), or attach a custom handler to the «matplotlib» logger. This may be useful if you use a custom logging configuration.

If you compiled Matplotlib yourself, please also provide:

any changes you have made to setup.py or setupext.py .

The beginning of the build output contains lots of details about your platform that are useful for the Matplotlib developers to diagnose your problem.

your compiler version — e.g., gcc —version .

Including this information in your first e-mail to the mailing list will save a lot of time.

You will likely get a faster response writing to the mailing list than filing a bug in the bug tracker. Most developers check the bug tracker only periodically. If your problem has been determined to be a bug and can not be quickly solved, you may be asked to file a bug in the tracker so the issue doesn’t get lost.

Problems with recent git versions#

First make sure you have a clean build and install (see How to completely remove Matplotlib ), get the latest git update, install it and run a simple test script in debug mode:

and post build.out and run.out to the matplotlib-devel mailing list (please do not post git problems to the users list).

Of course, you will want to clearly describe your problem, what you are expecting and what you are getting, but often a clean build and install will help. See also Getting help .

© Copyright 2002–2012 John Hunter, Darren Dale, Eric Firing, Michael Droettboom and the Matplotlib development team; 2012–2023 The Matplotlib development team.

Источник

How to fix Matplotlib modulenotfound import errors?

In today’s post i would like to provide some troubleshooting information for people installing the matplotlib library package in their computers.

ModuleNotFoundError: no module named ‘matplotlib’ pyplot

This error is thrown when Python can’t find the Matplotlib package in your development environment. Most probably you’ll be able to troubleshoot this error by downloading the library from the Python repository using the PIP utility.

Install matplotlib with pip

In order to troubleshoot this error follow this process (explained for Windows, might require minor adjustments for MAC and Linux). Note that the process is identical for most Python add on libraries / packages such as Seaborn, NumPy, Pandas and many others.

  • Save your work, and close your Jupyter Notebooks/Lab, Spyder or other development environment you might be using.
  • Open your Command Prompt.
  • Type cmd.
  • Then in the command prompt type, type the following command:
  • Now, go ahead and hit Enter.
  • Python will download the latest version of the matplotlib library from the Python package repository.
  • Once done, open your development environment and import matplotlib.
  • That’s it!

Anaconda environments

If you are have installed Anaconda, then by default, the basic Data Analysis packages, including Pandas and Matplotlib are already installed in your base environment. If for some reason you still receive an import error proceed as following.

  • From the Start mane, open Anaconda Navigator.

  • On the left hand side, hit the Environments tab (step 1)
  • Then highlight your Anaconda environment (step 2).
  • Then in the dropdown box (step 3), select Not Installed.
  • In the Search box, type matplotlib and hit Enter.
  • Then check the box near the package and hit Apply.
  • Then in the Install Packages dialog, click Apply again.

  • Once Anaconda Navigator is done, close it and reopen your development environment and download matplotlib.

Note: for completeness, you can also update your Anaconda environment manually (this is specially useful if you use MiniConda.

  • From the Windows Start Menu open the Anaconda Prompt
  • Type the following command
  • Hit Enter.
  • Now type
  • Hit Enter.
  • Matplotlib will be downloaded and installed.
  • That’s it.

Importerror no module named matplotlib.pyplot / matplotlib.path

This error is the base class of the ModuleNotFound error, and available since Python 3.3. The troubleshooting process we just described will remedy this error as well.

Questions? Feel free to leave us a comment

report this ad

Источник

[Solved] ImportError: No module named matplotlib.pyplot

Table of Contents Hide

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.

ImportError: 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

Using Python 3

Alternatively, if you have easy_install in your system, you can install matplotlib using the below command.

Using easy install

For CentOs

For Ubuntu

To install matplotlib module on Debian/Ubuntu :

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.

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.

Install Matplotlib in Anaconda

Matplotlib is available both via the anaconda main channel and it can be installed using the following command.

You can also install it via the conda-forge community channel by running the below command.

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.

Источник

modulenotfounderror: no module named ‘matplotlib’

In this Python tutorial, we will discuss the modulenotfounderror: no module named ‘matplotlib’ and we shall also cover the following topics:

  • modulenotfounderror: no module named matplotlib windows 10
  • modulenotfounderror: no module named ‘matplotlib’ ubuntu
  • modulenotfounderror no module named ‘matplotlib’ python 3
  • modulenotfounderror no module named ‘matplotlib’ jupyter notebook
  • modulenotfounderror no module named ‘matplotlib’ anaconda
  • modulenotfounderror: no module named ‘matplotlib’ pycharm
  • modulenotfounderror: no module named ‘matplotlib.pyplot’; ‘matplotlib’ is not a package

Table of Contents

modulenotfounderror: no module named matplotlib windows 10

Check if you have pip installed already, simply by writing pip in the python console. If you don’t have pip, get a python script called get-pip.py from the internet and save it to your local system. pip is the python package installer.

Take note of where the file got saved and change the current directory to that directory from the command prompt.

Run the get-pip.py script to install pip by writing the following code in cmd (command prompt) to install pip:

Now in cmd type the following code to install matplotlib with its dependencies:

The error will be resolved, if not then follow through the end of this post.

modulenotfounderror: no module named ‘matplotlib’ ubuntu

If you don’t have matplotlib installed then to install Matplotlib for Python 3 through the APT package manager, you need the package python3-matplotlib:

If you want to install it with pip for python 2.7, you need to use pip:

If the error still arises, follow through to the end of the post.

modulenotfounderror no module named ‘matplotlib’ python 3

You can install matplotlib with pip for python 3 and above, you just need to use pip3.

Open the python console and execute the command given below:

By executing the above code, the matplotlib for your python will be installed.

modulenotfounderror no module named ‘matplotlib’ jupyter notebook

Create a virtual environment inside your project directory. If you don’t have it, you have to install virtualenv by executing the following command in the cmd/terminal.

Install matplotlib inside of your virtual environment.

Now, install ipykernel inside your virtual environment.

Connect your jupyter kernel to your new environment.

When you start your jupyter notebook, you will see the option to select an environment, select the environment you have created which has matplotlib installed. Now, you are good to go with it.

modulenotfounderror no module named ‘matplotlib’ anaconda

If you have Python installed previously, before installing Anaconda, the reason could be that it’s running your default Python installation instead of the one installed with Anaconda. You have to try prepending this to the top of your script:

If that does not work, restart the terminal and try installing matplotlib with conda in conda prompt or cmd, and see if it works.

If the problem still not resolves, maybe you have to create a virtual environment as given in the above topics.

modulenotfounderror: no module named ‘matplotlib’ pycharm

You can get this error if you are using pycharm and have matplotlib.py in your current working directory. You have to just delete or rename the matplotlib.py file to resolve the issue, most probably it will work.

modulenotfounderror: no module named ‘matplotlib.pyplot’; ‘matplotlib’ is not a package

The error is caused because of the following reasons, check them out:

  • Make sure that the version of matplotlib you are installing is compaitible with your python version installed.
  • If the python installed is 64 bits version with matplotlib is 32bits. Make sure they are the same.
  • Make sure to add PATH variable for system and environment variables with path to the python.
  • If pip version is outdated, upgrade it to the latest version.
  • Also make sure that there is no typos in the import statement.
  • If the error still exist then, try to check if there is any file matplotlib.py in your working directory. Remove that file, restart the kernel and import matplotib again. That should work.

You may also like reading the following articles.

In this Python tutorial, we have discussed the modulenotfounderror: no module named ‘matplotlib’ and we have also covered the following topics:

  • modulenotfounderror: no module named matplotlib windows 10
  • modulenotfounderror: no module named ‘matplotlib’ ubuntu
  • modulenotfounderror no module named ‘matplotlib’ python 3
  • modulenotfounderror no module named ‘matplotlib’ jupyter notebook
  • modulenotfounderror no module named ‘matplotlib’ anaconda
  • modulenotfounderror: no module named ‘matplotlib’ pycharm
  • modulenotfounderror: no module named ‘matplotlib.pyplot’; ‘matplotlib’ is not a package

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

The error “ModuleNotFoundError: No module named matplotlib» is a common error experienced by data scientists when developing in Python. The error is likely an environment issue whereby the matplotlib package has not been installed correctly on your machine, thankfully there are a few simple steps to go through to troubleshoot the problem and find a solution.

Your error, whether in a Jupyter Notebook or in the terminal, probably looks like one of the following:

No module named 'matplotlib'
ModuleNotFoundError: No module named 'matplotlib'

In order to find the root cause of the problem we will go through the following potential fixes:

  1. Upgrade pip version
  2. Upgrade or install matplotlib package
  3. Check if you are activating the environment before running
  4. Create a fresh environment
  5. Upgrade or install Jupyer Notebook package

Are you installing packages using Conda or Pip package manager?

It is common for developers to use either Pip or Conda for their Python package management. It’s important to know what you are using before we continue with the fix.

If you have not explicitly installed and activated Conda, then you are almost definitely going to be using Pip. One sanity check is to run conda info in your terminal, which if it returns anything likely means you are using Conda.

Upgrade or install pip for Python

First things first, let’s check to see if we have the up to date version of pip installed. We can do this by running:

pip install --upgrade pip

Upgrade or install matplotlib package via Conda or Pip

The most common reason for this error is that the matplotlib package is not installed in your environment or an outdated version is installed. So let’s update the package or install it if it’s missing.

For Conda:

# To install in the root environment 
conda install matplotlib 

# To install in a specific environment 
conda install -n MY_ENV matplotlib

For Pip:‌

# To install in the root environment
python3 -m pip install -U matplotlib

# To install in a specific environment
source MY_ENV/bin/activate
python3 -m pip install -U matplotlib

Activate Conda or venv Python environment

It is highly recommended that you use isolated environments when developing in Python. Because of this, one common mistake developers make is that they don’t activate the correct environment before they run the Python script or Jupyter Notebook. So, let’s make sure you have your correct environment running.

For Conda:

conda activate MY_ENV

For virtual environments:

source MY_ENV/bin/activate

Create a new Conda or venv Python environment with matplotlib installed

During the development process, a developer will likely install and update many different packages in their Python environment, which can over time cause conflicts and errors.

Therefore, one way to solve the module error for matplotlib is to simply create a new environment with only the packages that you require, removing all of the bloatware that has built up over time. This will provide you with a fresh start and should get rid of problems that installing other packages may have caused.

For Conda:

# Create the new environment with the desired packages
conda create -n MY_ENV python=3.9 matplotlib 

# Activate the new environment 
conda activate MY_ENV 

# Check to see if the packages you require are installed 
conda list

For virtual environments:

# Navigate to your project directory 
cd MY_PROJECT 

# Create the new environment in this directory 
python3 -m venv MY_ENV 

# Activate the environment 
source MY_ENV/bin/activate 

# Install matplotlib 
python3 -m pip install matplotlib

Upgrade Jupyter Notebook package in Conda or Pip

If you are working within a Jupyter Notebook and none of the above has worked for you, then it could be that your installation of Jupyter Notebooks is faulty in some way, so a reinstallation may be in order.

For Conda:

conda update jupyter

For Pip:

pip install -U jupyter

Best practices for managing Python packages and environments

Managing packages and environments in Python is notoriously problematic, but there are some best practices which should help you to avoid package the majority of problems in the future:

  1. Always use separate environments for your projects and avoid installing packages to your root environment
  2. Only install the packages you need for your project
  3. Pin your package versions in your project’s requirements file
  4. Make sure your package manager is kept up to date

References

Conda managing environments documentation
Python venv documentation

Понравилась статья? Поделить с друзьями:
  • No media present error 1962
  • No matching pci ids in driverpack ini file как исправить
  • No matching function for call to c ошибка
  • No matching feature found h0050 как исправить
  • No match for argument phpmyadmin error unable to find a match phpmyadmin