Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 39 ยท Widgets and Visualization

Plots in Notebooks

Draw charts inside Jupyter notebooks with Matplotlib: inline and interactive backends, the figure and axes objects, multiple plots, sizing, saving figures and common mistakes.

Seeing your data is half of understanding it, and notebooks make that easy: a plot appears right under the cell that drew it. In the Python world the foundation of almost every plotting tool is Matplotlib; pandas, seaborn and many others draw through it. This lesson explains how plots reach a notebook, how to build a clean chart with the object-oriented interface, and how to avoid the classic problems (blank figures, overlapping plots, huge files).

The runnable charts on this page use real Matplotlib in the browser (Pyodide), with the same plotting code you would write in a notebook. The notebook-specific parts (%matplotlib magics, ipympl) need a real kernel and are shown read-only. Inline rendering in a notebook is done by the kernel; here the site shows the finished picture below the code.

How plots get into the notebook

A Matplotlib backend decides what happens when you draw. Notebooks use a special one that turns the figure into an image and sends it to the front end as display_data (see Rich output and display). You choose it with a magic:

Python
%matplotlib inline      # static PNG images in the output (the default in recent IPython)
%matplotlib widget      # interactive figure: zoom, pan, resize (needs the ipympl package)

With inline, each figure is shown automatically when the cell finishes, so you do not need plt.show(), although it is harmless and, when you create several figures in one cell, gives you control over when each appears. Everything else, such as the shape of a chart, is ordinary Matplotlib.

The two interfaces

Matplotlib offers a quick "state machine" interface (plt.plot(...)) and an explicit object-oriented one. In notebooks, where you often make several figures, the explicit style avoids confusion about "the current plot":

  • a Figure is the whole canvas;
  • an Axes is one plot area inside it, with its own x- and y-axis, title and labels.

Create both with plt.subplots(), then call methods on the axes:

Python A first chart with the object-oriented interface

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.

figsize is in inches; tight_layout() prevents labels from being cut off. For crisper images on high-resolution screens set plt.rcParams["figure.dpi"] = 120, or use the retina format of inline plots: %config InlineBackend.figure_format = "retina" (read-only, IPython-only).

Several plots: subplots and several figures

Put related charts side by side with a grid of axes. sharey=True makes the y-axes comparable:

Python Two charts side by side

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.

If a cell creates two figures with plt.figure() calls (or plt.subplots() twice), inline mode shows both, in creation order. To avoid showing a figure at all (for example while saving a file), call plt.close(fig). Forgetting to close figures in a loop eventually triggers the warning "More than 20 figures have been opened" and eats memory.

Common plot types at a glance

You want to show Method
A trend over time ax.plot(x, y)
Compare categories ax.bar(names, values) or ax.barh(...)
Distribution of one variable ax.hist(values, bins=20)
Relationship of two variables ax.scatter(x, y)
Share of a whole (use sparingly) ax.pie(values, labels=...)
Spread and outliers ax.boxplot(groups)
Matrix of values ax.imshow(matrix)

Choose the chart for the question, not the other way around. A scatter plot answers "are these two related?"; a histogram answers "what does this look like?".

A histogram with deterministic data

Notebooks are for exploration, so you will often check a distribution first. To keep results repeatable, seed the random generator (see the reproducibility chapter later in this course):

Python A histogram of seeded random data

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.

Saving figures

A notebook displays figures but does not save them as files. To use a chart in a report, save it explicitly:

Python
fig.savefig("visits.png", dpi=200, bbox_inches="tight")
fig.savefig("visits.svg")        # vector format, scales without blur
fig.savefig("visits.pdf")

Use PNG for web, SVG or PDF for documents. Keep the savefig call in the same cell as the plot, or the figure may already be closed.

Interactive figures with ipympl

With the ipympl package installed (%pip install ipympl), %matplotlib widget replaces the static image with a figure that has a toolbar: pan, zoom, save. It is great for exploring a dense scatter plot. The cost: the widget lives in the browser and needs a running kernel, so it is not saved as a static picture, and in shared HTML exports it appears blank. Use inline for notebooks you share, and the widget backend for private exploration. For interactive charts that survive export, libraries such as Plotly and Altair are covered in Interactive charts and progress bars.

Frequent problems

Problem Cause and fix
No figure appears The backend is not inline; run %matplotlib inline. Or the cell raised an error before drawing.
Two plots drawn on top of each other Both called plt.plot on the current axes. Use fig, ax = plt.subplots() for each chart.
Last cell's changes appear in an old plot The old figure is still the "current figure". Create a new figure first.
Text cut off at the edges Add fig.tight_layout() or bbox_inches="tight" when saving.
Notebook file is huge Many high-resolution plots are stored as base64. Lower dpi, or clear outputs before saving (see The .ipynb file format).
Plots differ on every run Random data without a seed. Seed it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does %matplotlib inline do?

    The inline backend renders figures to images and displays them in the cell's output.
  2. 2. Why prefer fig, ax = plt.subplots() in notebooks?

    Explicit figure and axes objects avoid confusion about which chart a call affects.
  3. 3. A notebook created for sharing as HTML should use which backend for figures?

    Inline images are saved in the notebook and show up in exports; widget figures need a live kernel.
  4. 4. How do you keep a chart as a file for a report?

    Displaying a figure does not save it. Call savefig, choosing PNG, SVG or PDF.

Summary

  • Notebooks display Matplotlib figures through a backend: %matplotlib inline (static) or widget (interactive, needs ipympl).
  • Use fig, ax = plt.subplots() and call methods on the axes for clear, repeatable charts.
  • Use subplots for side-by-side comparison and tight_layout() for clean spacing.
  • Close figures you do not need, seed random data, and save files with savefig.
  • Pick the chart type from the question you want to answer.
  • Large images inflate the .ipynb; clear outputs before sharing.

Next: Interactive widgets with ipywidgets