Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 57 ยท Annotation and Polish

Shapes, Patches and Custom Drawing

Draw custom shapes in Matplotlib with Rectangle, Circle, Ellipse, Polygon, Arc and FancyArrow, add_patch, PatchCollection, transforms, clipping and diagrams.

Charts are not the only thing Matplotlib draws. Every bar, wedge and legend swatch you have seen is a patch: a filled shape that is also an object you can create yourself. With a handful of patch classes you can draw highlight boxes, region markers, flowcharts, floor plans and diagrams, mixing them freely with ordinary data plots.

This lesson introduces the main patch classes, how to add them to an Axes, how coordinates and aspect ratio affect them, a first look at transforms, collections for many shapes, clipping, and a small diagram built entirely from shapes. For the Artist concept behind it, see Anatomy of a Figure.

Patches in the toolbox

Rectangle Corner, width, height.
Circle and Ellipse Center and size.
Polygon Any list of corners.
FancyArrow A block arrow.

Create the patch, then ax.add_patch(patch).

1 / 2

Creating and adding a patch

A patch is created like any object, then handed to the Axes with ax.add_patch(...). Creating one does not draw it; adding it does. Unlike plot, add_patch does not rescale the axes, so set the limits yourself, and use ax.set_aspect("equal") so circles are round.

Python Rectangle, Circle, Ellipse and Polygon

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 arguments differ per class:

  • Rectangle((x, y), width, height): (x, y) is the lower-left corner.
  • Circle((x, y), radius): the center and the radius.
  • Ellipse((x, y), width, height, angle=degrees): full widths, not radii; angle rotates it.
  • Polygon([(x1, y1), ...]): the corners in order; closed=True joins the last to the first.

Common styling arguments are facecolor, edgecolor, linewidth, linestyle, alpha, fill=False for outlines only, and hatch="//" for patterns.

Arcs, wedges and arrows

Arc draws only an outline of part of an ellipse (it ignores the face color). Wedge draws a pie slice, and FancyArrow a block arrow with a head.

Python Arc, Wedge and FancyArrow

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.

Angles run counter-clockwise from the positive x axis and are measured in degrees. length_includes_head=True makes the total arrow length match the numbers you give. For arrows that connect two points (and curve) ax.annotate or FancyArrowPatch are usually easier; see Annotations and Arrows.

Patches in data coordinates

Because patches live in data coordinates, they combine with real data. A rectangle can mark a region on a scatter plot or a plateau on a time series; a circle can ring an outlier.

Python Rings and boxes on a scatter 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.

set_aspect("equal") matters. With an automatic aspect, a Circle in data coordinates turns into an oval as soon as the x and y scales differ. If you want a circle that stays round whatever the aspect, use a transform (below).

A first look at transforms

Every patch has a transform that converts its coordinates to screen pixels. The default is ax.transData: coordinates mean data values. You can switch it:

  • transform=ax.transAxes: coordinates are fractions of the Axes, 0 to 1.
  • transform=fig.transFigure: fractions of the whole figure.

A rectangle with transform=ax.transAxes always fills the same part of the panel, whatever the data limits.

Python Axes-relative shapes and clipping

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.

set_clip_path restricts an artist to the inside of a patch. That is how some "image in a shape" and "cropped to a circle" effects are made. Transforms go much deeper; see Transforms and the Artist Layer.

Many shapes at once: PatchCollection

Adding thousands of patches one at a time is slow. A PatchCollection wraps a list of patches into a single artist that draws faster, and lets you color them by value with a colormap.

Python A grid of circles colored by value

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.

Notice ax.add_collection replaces add_patch, and set_array supplies the numbers mapped to colors. As with other artists, a colorbar can be built from the collection (see Colormaps and Color Normalization).

A diagram from shapes

With FancyBboxPatch for rounded boxes, text at the box centers, and arrows between them, a small flowchart takes a few lines. Putting the box drawing in a helper function keeps it readable.

Python A three-step flow diagram

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.

FancyArrowPatch connects two points with an arrow, where FancyArrow draws a block shape. For long diagrams, a dedicated tool is better, but for charts that need a small schematic, drawing it in Matplotlib keeps everything in one figure.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In Rectangle((2, 3), 4, 1), what is (2, 3)?

    A Rectangle is positioned by its lower-left corner and then given a width and a height.
  2. 2. Why call ax.set_aspect('equal') when drawing a Circle in data coordinates?

    Patches use data coordinates. If the axes have different scales per unit, shapes are distorted; equal aspect makes the scales the same.
  3. 3. Does ax.add_patch rescale the axes to fit the patch?

    Unlike plot or scatter, add_patch does not update the data limits automatically, so call set_xlim and set_ylim.
  4. 4. What is a PatchCollection for?

    One collection artist draws many shapes efficiently, and set_array with a cmap colors them by value.

Summary

  • Patches are shape artists: Rectangle, Circle, Ellipse, Polygon, Arc, Wedge, FancyArrow and more.
  • Create the patch, then call ax.add_patch(patch); it does not rescale the axes, so set limits and an equal aspect.
  • Patches live in data coordinates by default; transform=ax.transAxes uses fractions of the Axes instead.
  • set_clip_path restricts an artist to the inside of a shape.
  • PatchCollection draws many shapes fast and supports colormaps.
  • FancyBboxPatch, text and FancyArrowPatch build small diagrams.

Next, make every chart on your site look consistent with Styles, rcParams and Themes.