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 trying to work basic python – jupyter projects.
I am stuck on following error during matplotlib:
screenshot on jupyter-error
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
asked Feb 18, 2017 at 23:17
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
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
5425 silver badges12 bronze badges
answered Sep 29, 2018 at 16:45
bhaskarcbhaskarc
9,19910 gold badges64 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
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
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).
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 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
- in jupter notebook type
print(sys.executable)
this gave me the following
/Users/myusername/opt/anaconda3/bin/python
-
open terminal, go into the folder
/Users/myusername/opt/anaconda3/bin/ -
type the following:
python3 -m pip install matplotlib -
restart jupyter notebook (mine is vs code mac ox)
answered Jan 4, 2021 at 10:31
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
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
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:
- Upgrade pip version
- Upgrade or install matplotlib package
- Check if you are activating the environment before running
- Create a fresh environment
- 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:
- Always use separate environments for your projects and avoid installing packages to your root environment
- Only install the packages you need for your project
- Pin your package versions in your project’s requirements file
- Make sure your package manager is kept up to date
References
Conda managing environments documentation
Python venv documentation
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
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.