Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 57 ยท Line Plots and Basic Styling

Legends and Grids

Add and place Matplotlib legends, move them outside the axes, build custom handles with Line2D and Patch, style major and minor grids, and use figure legends.

When a chart has more than one series, the reader needs a key: which line is which? That is the job of the legend. A grid does a different but related job: it gives the eye reference lines so values can be read off the axes. Both are easy to add and easy to overdo, so this lesson shows how to do them well.

You should already know how to style lines and label axes. Here we connect those styles to the key, and finish the "Line Plots and Basic Styling" chapter before bar charts begin the next one.

A legend in two steps

Label Pass label= when plotting.
Legend Call ax.legend() once.

Artists with no label stay out of the legend.

1 / 2

The basic legend

Give every artist you want in the legend a label, then call ax.legend(). Matplotlib collects each labelled line, bar or marker and draws a box with a sample and its text. Labels starting with an underscore are ignored on purpose, which is how helper lines such as a zero baseline stay out of the key.

Useful keywords of ax.legend:

Keyword Effect
loc "upper right", "lower left", "center", "best" and so on
ncol Number of columns of entries
title A heading for the legend box
frameon False removes the box
fontsize Text size
labelspacing, columnspacing Gaps between entries

loc="best" (the default) tries to avoid covering data, but it becomes slow on big data and may jump around between runs. For stable, publishable charts, choose a location yourself.

Python Labels, loc, ncol and title

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.

The grey zero line has a label that starts with an underscore, so it does not appear in the legend. The entries sit in three columns along the bottom, and ylim leaves empty room for them so they cover no data.

Legends outside the axes

bbox_to_anchor=(x, y) positions the legend relative to the axes in axes fractions, where (0, 0) is the lower-left and (1, 1) the upper-right of the plot area. Combined with loc, which says which corner of the legend touches that anchor, you can place the legend outside:

Python
ax.legend(loc="upper left", bbox_to_anchor=(1.02, 1.0), borderaxespad=0)

This anchors the legend's upper-left corner just to the right of the axes. Since the legend now lies outside the axes, it can be clipped when you save the figure. Use fig.tight_layout() or constrained_layout=True (see Figure Size, DPI and Layout), or save with bbox_inches="tight".

Python A legend outside the axes

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.

Custom legend handles

You do not have to draw a thing to explain it. A legend can show proxy artists: small objects built only for the key. Line2D([0], [0], ...) makes a line or marker sample, and Patch(...) makes a filled box. Pass them with ax.legend(handles=[...]). This is how you explain a color scheme used across many artists (all red points mean "failed") with only a few entries, or describe symbols that were drawn with a collection.

You can also pick up the automatic handles with ax.get_legend_handles_labels(), filter or reorder them, and pass them back.

Python Proxy handles and reordering

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.

Four entries explain forty points, because each handle is a small stand-in built to look like the real marker. The Patch matches the shaded band, which axvspan would otherwise have to label itself.

Grids

ax.grid(True) draws lines at the major ticks. Style them like any line: color, linestyle, linewidth and alpha. Choose which ticks with which="major", "minor" or "both", and which direction with axis="x", "y" or "both". Minor grid lines only show when minor ticks exist, so turn those on first (see Ticks, Locators and Formatters).

Subtle grids work best: thin, light and drawn behind the data. ax.set_axisbelow(True) makes sure grid lines are behind bars and lines instead of cutting through them.

Python Major and minor grid lines

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.

For bar charts a horizontal grid helps compare heights, while vertical lines would only add clutter. Think about which direction the eye needs.

Figure-level legends

When several panels share the same lines, repeating a legend in each is noise. fig.legend(handles, labels, loc=...) creates one legend for the whole figure. Gather handles from one axes with ax.get_legend_handles_labels(), then place it with loc="outside upper center" (when using constrained layout) or an explicit bbox_to_anchor.

Python
handles, labels = axes[0].get_legend_handles_labels()
fig.legend(handles, labels, loc="outside lower center", ncol=3)

That pattern pairs well with multiple subplots that use the same colors. A last tip: if the lines are few and far apart, labelling them directly at their ends is often clearer than any legend; see Annotations and Arrows.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do you keep a helper line out of the legend?

    Matplotlib ignores artists whose label begins with an underscore, and artists with no label at all.
  2. 2. Which call places the legend's upper-left corner just outside the right edge of the axes?

    bbox_to_anchor gives the anchor point in axes fractions, and loc names the legend corner placed at that point.
  3. 3. What are Line2D and Patch used for in a legend?

    They are artists built only for the legend, so you can explain a scheme with a few entries.
  4. 4. Why use ax.set_axisbelow(True) with a grid?

    By default grid lines may draw on top of bars; set_axisbelow(True) sends them behind the data.
  5. 5. Why is loc="best" not always ideal?

    best searches for a free corner, which costs time on large data and may jump around, so fixed positions are more predictable.

Summary

  • Give artists a label and call ax.legend(); underscore labels are ignored.
  • loc, ncol, title and frameon shape the legend; bbox_to_anchor with loc moves it outside the axes.
  • Line2D and Patch proxy handles explain styles that were not drawn as single artists; get_legend_handles_labels lets you filter and reorder.
  • ax.grid takes which, axis and line-style options; keep grids light and behind the data with set_axisbelow(True).
  • fig.legend gives several panels one shared key.

Next, move on to chart types with Bar Charts.