Modulenotfounderror no module named matplotlib ошибка

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

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’ не определено

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 am currently trying to work basic python — jupyter projects.

I am stuck on following error during matplotlib:

screenshot on jupyter-error enter image description here

ModuleNotFoundError: No module named ‘matplotlib

I tried to update, reinstall matplotlib aswell in conda and in pip but it still not working.

happy over every constructive feedback

Renats Stozkovs's user avatar

asked Feb 18, 2017 at 23:17

Bullfraud's user avatar

3

open terminal and change the directory to Scripts folder where python installed. Then type the following command and hit enter

pip install matplotlib

Hope this will solve the issue.

answered Sep 7, 2018 at 16:55

Shahriar Miraj's user avatar

1

I was facing the exact issue. It turns out that it was using the system Python version despite me having activated my virtual environment.

This is what eventually worked.

If you are using a virtual environment which has a name say myvenv, first activate it using command:

source activate myvenv

Then install module ipykernel using the command:

pip install ipykernel

Finally run (change myvenv in code below to the name of your environment):

ipykernel install --user --name myvenv --display-name "Python (myvenv)" 

Now restart the notebook and it should pick up the Python version on your virtual environment.

hahnec's user avatar

hahnec

5425 silver badges12 bronze badges

answered Sep 29, 2018 at 16:45

bhaskarc's user avatar

bhaskarcbhaskarc

9,21910 gold badges65 silver badges86 bronze badges

While @Frederic’s top-voted solution is based on JakeVDP’s blog post from 2017, it completely neglects the %pip magic command mentioned in the blog post. Since 2017, that has landed in mainline IPython and the easiest way to access the correct pip instance connected to your current IPython kernel and environment from within a Jupyter notebook is to do

%pip install matplotlib

Take a look at the list of currently available magic commands at IPython’s docs.

answered Aug 27, 2022 at 5:03

Dominik Stańczak's user avatar

0

generally speaking you should try to work within python virtual environments. and once you do that, you then need to tell JupyterLab about it. for example:

# create a virtual environment
# use the exact python you want to work with in this step
python3.9 -m venv myvenv
# 'activate' (or 'enter') it
source myvenv/bin/activate
# install the exact stuff you want to use in that environment
pip install matplotlib
# now tell JupyterLabs about the environment
python -m ipykernel install --user --name="myenv" --display-name="My project (myenv)"
# start it up 
jupyter notebook mynotebook
# if you now look under 'Kernel->Change kernel', your 'myenv' should be there
# select it (restart kernel etc if needed) and you should be good

answered Sep 18, 2021 at 1:54

Peter S Magnusson's user avatar

1

The issue with me was that jupyter was taking python3 for me, you can always check the version of python jupyter is running on by looking on the top right corner (attached screenshot).

enter image description here

When I was doing pip install it was installing the dependencies for python 2.7 which is installed on mac by default.
It got solved by doing:

> pip3 install matplotlib

answered Sep 17, 2019 at 6:57

Siddharth Sharma's user avatar

Siddharth SharmaSiddharth Sharma

1,6532 gold badges19 silver badges35 bronze badges

Having the same issue, installing matplotlib before to create the virtualenv solved it for me. Then I created the virtual environment and installed matplotlib on it before to start jupyter notebook.

answered Jan 11, 2019 at 10:33

  1. in jupter notebook type

print(sys.executable)

this gave me the following
/Users/myusername/opt/anaconda3/bin/python

  1. open terminal, go into the folder
    /Users/myusername/opt/anaconda3/bin/

  2. type the following:
    python3 -m pip install matplotlib

  3. restart jupyter notebook (mine is vs code mac ox)

answered Jan 4, 2021 at 10:31

Fen's user avatar

FenFen

811 silver badge1 bronze badge

1

If module installed an you are still getting this error, you might need to run specific jupyter:

python -m jupyter notebook

and this is also works

sudo jupyter notebook --allow-root

answered Aug 26, 2022 at 23:40

Mustafa Candan's user avatar

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

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!

Понравилась статья? Поделить с друзьями:
  • Module datetime has no attribute now ошибка
  • Modular voice chat ошибка переподключение
  • Modr клуб романтики ошибка
  • Modifier is disabled skipping apply blender ошибка
  • Modern warfare код ошибки