Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 57 ยท Getting Started

Installing Matplotlib and Using Jupyter

Install Matplotlib with pip in a virtual environment, test it, choose a backend, use %matplotlib inline or widget in Jupyter, and fix plots that do not show up.

The examples on this site draw their pictures in your browser. On your own computer, drawing a plot involves a few more moving parts: the package itself, a backend that decides where the picture goes (a window, a notebook cell or a file), and an environment such as Jupyter. Most "my plot does not appear" problems come from a mismatch among those parts. This lesson explains them so that you can set up Matplotlib once and understand what to do when something goes wrong.

Install Matplotlib

Use one virtual environment per project so that package versions never fight each other. In a terminal:

Terminal
mkdir plot-lab
cd plot-lab
python -m venv .venv

source .venv/bin/activate          # macOS and Linux
.venv\Scripts\Activate.ps1         # Windows PowerShell

python -m pip install matplotlib

Matplotlib needs NumPy, and pip installs it for you. A common data-visualization setup also includes pandas and JupyterLab:

Terminal
python -m pip install matplotlib numpy pandas jupyterlab

The python -m pip form makes sure that pip belongs to the Python you are about to use. If you use uv, run uv venv and uv pip install matplotlib instead.

Test the installation

This short program prints the versions and the active backend, draws a plot, and shows that the figure can be saved to a file. It is the same check you would run on your own machine:

Python Your first test plot

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

On your computer, plt.show() opens a window (or displays the plot in a notebook). In the browser, the page captures the figure and shows it as an image. Printing the backend tells you which mechanism is active, and the next section explains what it means.

If the script runs without an ImportError and a plot appears, you are done.

What is a backend?

A backend is the part of Matplotlib that turns your figure into something real. There are two kinds:

  • Interactive backends open a window or a widget so that you can zoom and pan: QtAgg, TkAgg, MacOSX, GTK4Agg, WebAgg, and the notebook widget backend.
  • Non-interactive backends only write files or produce images in memory: Agg (PNG), pdf, svg, ps, cairo.
flowchart TD
    P["Your plotting code<br/>(pyplot or Figure API)"] --> B{"Backend"}
    B -->|"interactive"| W["Window or widget<br/>(Qt, Tk, macOS, notebook)"]
    B -->|"non-interactive"| F["File or image<br/>(Agg, PDF, SVG)"]

The same plotting code works with any backend; the backend only decides where the result appears.

Matplotlib picks a default backend automatically: an interactive one if your system has a toolkit, Agg if it does not (for example on a server without a display). You can check it with matplotlib.get_backend() and change it:

Python
import matplotlib
matplotlib.use("Agg")        # call before importing pyplot

or for one run through an environment variable:

Terminal
MPLBACKEND=Agg python make_report.py        # macOS and Linux
$env:MPLBACKEND = "Agg"; python make_report.py   # Windows PowerShell

The most useful non-interactive case is a script on a server: with Agg you can create and save plots without any screen:

Python Render to a file without a window

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

plt.close(fig) matters in scripts that make many figures. Every open figure uses memory, and Matplotlib warns after 20 of them.

Using Matplotlib in Jupyter

Install and start JupyterLab with python -m pip install jupyterlab and jupyter lab (see Installing pandas and Using Jupyter for notebooks in more detail). Modern Jupyter shows plots inline by default, but you can choose the behaviour with a magic command in a cell:

Magic Behaviour
%matplotlib inline Static PNG images below the cell (the usual default).
%matplotlib widget Interactive figures with pan and zoom in the notebook; needs pip install ipympl.
%matplotlib qt A separate desktop window (when a Qt toolkit is installed).

Typical first cell of a notebook:

Python
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt

Magic commands are a Jupyter feature, not Python. They work in notebooks but give a syntax error in a plain .py file.

Notebook habits for plotting:

  • Create the figure and draw in one cell. Because Matplotlib's current figure persists between cells, drawing into "the current figure" in a later cell can add to an old plot by accident. Prefer fig, ax = plt.subplots() and use ax. methods, as in pyplot versus the object-oriented API.
  • In a notebook you usually do not need plt.show() with the inline backend, but adding it does no harm and keeps the code portable to scripts.
  • Do not leave a trailing expression that prints noise, such as <matplotlib.lines.Line2D at 0x...>. Finish with plt.show(), or end the line with a semicolon.
  • Restart the kernel and run all cells before you share a notebook, so that the plots are reproducible.

Fixing plots that do not appear

Symptom Likely cause and fix
Script ends and no window shows Missing plt.show(). Add it at the end.
Window opens and closes instantly Your script ended; plt.show() blocks only until the window closes. Keep plt.show() last.
UserWarning: FigureCanvasAgg is non-interactive You use a non-interactive backend. Fine for saving files; to see a window install a toolkit (pip install PyQt6) or set MPLBACKEND=QtAgg.
ImportError: ... tkinter or Qt platform plugin errors The chosen GUI toolkit is missing or broken. Switch backend, or use Agg and savefig.
Plots do not show on a remote server or in a container There is no display. Use Agg and save images, or use a notebook.
Notebook shows an empty figure The figure was created in one cell and drawn in another. Draw everything in the same cell.
Old plot lines appear in the new figure You are reusing the current figure. Create a new one with plt.subplots(), or call plt.close("all") first.
ModuleNotFoundError: No module named 'matplotlib' Wrong environment. Activate the right virtual environment and run python -m pip install matplotlib.

Tip: When you ask for help, include the output of matplotlib.__version__, matplotlib.get_backend() and how you run the code (script, notebook, IDE). Those three facts solve most plot-does-not-show questions.

Other places to run Matplotlib

  • VS Code shows plots from notebooks and from the interactive window. Choose your .venv interpreter first.
  • PyCharm has a scientific mode that shows plots in a panel.
  • Google Colab and other hosted notebooks come with Matplotlib installed and draw inline.
  • Scripts and servers use Agg (or pdf/svg) and savefig.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a Matplotlib backend decide?

    The backend turns the figure into something real. The plotting code is the same for every backend.
  2. 2. You run a plotting script on a server with no display. What is the best setup?

    Agg renders into memory and files without needing a screen. savefig writes the result.
  3. 3. What does the notebook magic %matplotlib inline do?

    Inline is the standard notebook mode: each figure appears as an image under the cell that created it.
  4. 4. Why call plt.close(fig) in a script that creates hundreds of plots?

    Figures stay in memory until closed. Closing them avoids memory growth and the warning about too many open figures.
  5. 5. A notebook plot shows old lines from a previous cell. What is the best habit?

    pyplot keeps a current figure across cells. Creating a fresh figure and drawing on its Axes avoids mixing plots.

Summary

  • Install with python -m pip install matplotlib inside a virtual environment; check with matplotlib.__version__.
  • A backend decides where a figure goes. Interactive backends open windows; Agg, pdf and svg write files.
  • Use matplotlib.use("Agg") or MPLBACKEND=Agg on servers, and always savefig plus plt.close(fig).
  • In Jupyter, %matplotlib inline gives static images and %matplotlib widget (with ipympl) gives interactive figures.
  • Create the figure and draw in the same cell, and prefer the object-oriented fig, ax style.
  • When a plot does not show, check plt.show(), the backend, the environment and the cell structure.

Next: Your First Plot puts the setup to work.