Solve the No module named matplotlib in Python
We get the no module named matplotlib when we try to invoke the matplotlib package (or one of its sub-libraries) from our script before installing it first. To solve this error you need to install the matplotlib package using conda or the PIP utility. Once done, you can invoke the package to render your charts.
Understanding the error
Matplotlib is a 3rd party library that is not installed as part of standard Python distributions. Hence, when you try to invoke matplotlib components like pyplot without previously installing matplotlib you will get the modulenotfound error.
You will get a similar error if using VSCode, Jupyter, Colab, PyCharm, Spyder, or just the plain Python command line.
Fixing the matplotlib module not found error
- Save your work and close your Python development environment.
- Open your Anaconda Prompt (Windows) or Terminal (mac OS or Linux)
- Activate your conda environment by running the following command
conda activate <your_conda_env_directory>
- Your next step is to install the matplotlib package using the following command:
conda install matplotlib
- Your package and its dependencies will be collected from the conda repository.
- When prompted, authorize the installation.
- Once done, close the Anaconda Prompt and open your notebook.
- Lastly, import the matplotlib library into your Python program.
VirtualEnv / PIP users:
- Save your work and close your Python Editor.
- Invoke the Windows command prompt or the terminal.
- Windows Users only: If Python wasn’t added to the Windows path, change to the Python directory using the CD command
- Install the matplotlib package using PIP:
pip install matplotlib
- Once the package contents is collected and installed, close the command prompt.
- Open your Python development environment and import matplotlib to start creating your plots.
How to update Matplotlib to the latest version?
You can upgrade the matplotlib library to its latest version by running the following command:
pip install --upgrade matplotlib
How to deal with permission issues when installing matplotlib?
In case that you are encountering operation system permissions when installing matplolib, you can use the following commands.
Unix / Linux:
sudo pip install matplotlib
Open the command prompt (or the Anaconda prompt) as an Administrator, and install matplotlib:
pip install matplotlib