To draw a shape in Matplotlib, create a patch from matplotlib.patches, such as Rectangle, Circle, Ellipse, or Polygon, and add it to the axes with ax.add_patch(patch). Positions and sizes are in data coordinates, so a shape lines up with whatever else you've plotted. The code was written for Matplotlib 3.11.
Quick Example
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, Polygon, Rectangle
fig, ax = plt.subplots(figsize=(5, 5))
ax.add_patch(Rectangle((2, 0), 6, 4, facecolor="#e9c46a", edgecolor="#264653", linewidth=2)) # walls
ax.add_patch(Polygon([(1.5, 4), (5, 7), (8.5, 4)], closed=True, facecolor="#e76f51", edgecolor="#264653", linewidth=2)) # roof
ax.add_patch(Rectangle((4.2, 0), 1.6, 2.6, facecolor="#264653")) # door
ax.add_patch(Circle((8.8, 8.6), 0.9, facecolor="#f4a261", edgecolor="none")) # sun
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
ax.set_aspect("equal")
ax.axis("off")
plt.show()

Every shape follows the same two steps: build the patch with its geometry and style, then ax.add_patch() it. Two lines here matter for what comes next. set_xlim and set_ylim are there because add_patch doesn't resize the axes, and set_aspect("equal") keeps the circle round. Both are covered below.
Which Patch Draws Which Shape?
All of these live in matplotlib.patches. Positions are (x, y) in data units unless noted.
| Shape | Constructor | Notes |
|---|---|---|
| Rectangle | Rectangle((x, y), width, height, angle=0) |
(x, y) is the lower-left corner |
| Circle | Circle((x, y), radius) |
Center and radius |
| Ellipse | Ellipse((x, y), width, height, angle=0) |
Full widths, not radii; angle in degrees |
| Polygon | Polygon([(x1, y1), (x2, y2), ...], closed=True) |
Any list of vertices |
| Regular polygon | RegularPolygon((x, y), numVertices, radius=r) |
Hexagons, pentagons, diamonds |
| Wedge | Wedge((x, y), r, theta1, theta2, width=None) |
Pie slice; width turns it into a ring slice |
| Ring | Annulus((x, y), r, width) |
Full ring |
| Rounded box | FancyBboxPatch((x, y), w, h, boxstyle="round,...") |
Rounded or beveled rectangles |
| Arrow | FancyArrowPatch(posA, posB, arrowstyle="->") |
See annotation arrows |
from matplotlib.patches import Annulus, Ellipse, FancyBboxPatch, RegularPolygon, Wedge
shapes = {
"Rectangle": Rectangle((0.1, 0.2), 0.8, 0.55),
"Circle": Circle((0.5, 0.5), 0.4),
"Ellipse": Ellipse((0.5, 0.5), 0.9, 0.5, angle=25),
"Polygon": Polygon([(0.1, 0.15), (0.9, 0.25), (0.6, 0.85)]),
"RegularPolygon": RegularPolygon((0.5, 0.5), numVertices=6, radius=0.42),
"Wedge": Wedge((0.5, 0.5), 0.42, theta1=30, theta2=300),
"Annulus": Annulus((0.5, 0.5), r=0.42, width=0.14),
"FancyBboxPatch": FancyBboxPatch((0.12, 0.25), 0.76, 0.5, boxstyle="round,pad=0.02,rounding_size=0.15"),
}
fig, axes = plt.subplots(2, 4, figsize=(10, 5.4), layout="constrained")
for ax, (name, patch) in zip(axes.flat, shapes.items()):
patch.set(facecolor="#2a9d8f", edgecolor="#264653", linewidth=2)
ax.add_patch(patch)
ax.set(xlim=(0, 1), ylim=(0, 1), title=name)
ax.set_aspect("equal")
ax.axis("off")
plt.show()

Ellipse takes full width and height, so width=0.9 spans 0.9 data units, where Circle takes a radius. A Wedge angle runs counterclockwise from the positive x axis, so theta1=30, theta2=300 removes the slice from 300 to 30 degrees on the right. Pass width= to Wedge to cut out the middle and draw a donut slice.
Style a Patch: Fill, Edge, Hatch, and Transparency
Patches accept the usual artist properties as keyword arguments or through patch.set(...):
styles = [
("solid fill", dict(facecolor="#457b9d", edgecolor="#1d3557", linewidth=3)),
("outline only", dict(fill=False, edgecolor="#e63946", linewidth=3)),
("dashed outline", dict(fill=False, edgecolor="#1d3557", linewidth=3, linestyle="--")),
("hatched", dict(facecolor="white", edgecolor="#2a9d8f", linewidth=2, hatch="//")),
("alpha=0.3", dict(facecolor="#e76f51", edgecolor="#e76f51", linewidth=3, alpha=0.3)),
("faint fill, solid edge", dict(facecolor=(0.91, 0.44, 0.32, 0.3), edgecolor="#e76f51", linewidth=3)),
]
fig, ax = plt.subplots(figsize=(10, 3.4))
for i, (label, style) in enumerate(styles):
ax.add_patch(Rectangle((i * 1.3, 0), 1, 1, **style))
ax.text(i * 1.3 + 0.5, -0.12, label, ha="center", va="top", fontsize=9)
ax.set(xlim=(-0.2, 7.5), ylim=(-0.5, 1.2))
ax.set_aspect("equal")
ax.axis("off")
plt.show()

fill=Falsedraws only the outline. Settingfacecolor="none"does the same thing.alphaapplies to the fill and the edge together. For a faint fill with a crisp edge, givefacecoloran RGBA tuple, as in the last square.hatchpatterns draw in theedgecolor. See hatch patterns for the full list.zorderdecides which shape sits on top. Patches default to 1, lines to 2, and text to 3.
Why Is My Shape Missing, or Squashed Into an Oval?
Two surprises catch nearly everyone. First, ax.add_patch doesn't rescale the axes, so a circle at (50, 50) on a fresh axes, which shows 0 to 1, is simply off screen. Second, data units aren't pixels: if one unit on x is wider than one unit on y, a Circle is drawn as an oval.
fig, axes = plt.subplots(1, 3, figsize=(12, 3.2), layout="constrained")
for ax in axes:
ax.add_patch(Circle((50, 50), 5, facecolor="#9d4edd", edgecolor="#3c096c", linewidth=2))
axes[0].set_title("add_patch only: off screen")
axes[1].autoscale_view()
axes[1].set_title("autoscale_view(): fits, but an oval")
axes[2].autoscale_view()
axes[2].set_aspect("equal")
axes[2].set_title("plus set_aspect('equal'): round")
plt.show()

The fixes are ax.autoscale_view() (or explicit set_xlim and set_ylim) to bring the shape into view, and ax.set_aspect("equal") to make a unit the same length on both axes. If your chart's axes can't be equal, such as dates against dollars, draw the shape in axes coordinates instead (see below) or use Ellipse with the width and height you need. See aspect ratio and equal axes for more.
Rotate a Rectangle
Rectangle takes angle in degrees, counterclockwise. By default it rotates around (x, y), the lower-left corner. Pass rotation_point="center" to spin it in place (Matplotlib 3.6 and later):
fig, ax = plt.subplots(figsize=(6, 4))
ax.add_patch(Rectangle((2, 1), 3, 1.5, fill=False, edgecolor="gray", linestyle=":", linewidth=2)) # no rotation
ax.add_patch(Rectangle((2, 1), 3, 1.5, angle=30, fill=False, edgecolor="#e76f51", linewidth=2.5))
ax.add_patch(Rectangle((2, 1), 3, 1.5, angle=30, rotation_point="center", fill=False,
edgecolor="#2a9d8f", linewidth=2.5))
ax.plot(2, 1, "ko")
ax.set_xlim(0, 7)
ax.set_ylim(0, 5)
ax.set_aspect("equal")
plt.show()

The orange rectangle pivots around the black dot at its corner. The green one turns around its own center, so it stays centered over the dotted original.
Highlight a Region on a Chart With Patches
Because patches use data coordinates, they work as annotations on top of a real plot: a target zone as a Rectangle, a cluster of points circled with an Ellipse. Pass transform=ax.transAxes to place a shape in axes fractions (0 to 1) instead, which is useful for banners and frames:
import numpy as np
rng = np.random.default_rng(8)
distance = rng.uniform(1, 12, 120)
minutes = 8 + 2.5 * distance + rng.normal(0, 3, 120)
late_distance = rng.uniform(3, 5, 6)
late_minutes = rng.uniform(48, 58, 6) # orders stuck in traffic
fig, ax = plt.subplots(figsize=(8, 5))
ax.scatter(distance, minutes, s=25, color="#457b9d")
ax.scatter(late_distance, late_minutes, s=25, color="#457b9d")
# Target zone, in data coordinates
ax.add_patch(Rectangle((0, 0), 5, 25, facecolor="#2a9d8f", alpha=0.2, edgecolor="none"))
ax.text(0.2, 1.5, "Target: under 5 km, under 25 min", color="#1b6f64", fontsize=10)
# Ring around the slow orders
ax.add_patch(Ellipse((late_distance.mean(), late_minutes.mean()), 3.2, 16, fill=False,
edgecolor="#d62828", linewidth=2))
ax.text(5.6, 58, "Stuck in traffic", color="#d62828", fontsize=10)
# Banner above the plot, in axes coordinates
ax.add_patch(Rectangle((0, 1.02), 1, 0.08, transform=ax.transAxes, clip_on=False,
facecolor="#264653"))
ax.text(0.01, 1.06, "Delivery time vs distance", transform=ax.transAxes, color="white",
va="center", fontweight="bold")
ax.set_xlabel("Distance (km)")
ax.set_ylabel("Delivery time (minutes)")
ax.set_ylim(0, 65)
plt.show()

For a band that spans the whole axis in one direction, ax.axvspan and ax.axhspan are shorter, and they're covered in highlighting a date range. Use Rectangle when the shape has limits in both directions. clip_on=False lets the banner draw outside the plot area.
Draw Hundreds of Shapes With PatchCollection
Calling add_patch in a loop works for dozens of shapes. For hundreds or thousands, wrap them in a PatchCollection, which draws them in one pass and can color them from an array through a colormap. This example draws a parking lot, with each space colored by how long its car has been parked:
from matplotlib.collections import PatchCollection
rng = np.random.default_rng(12)
rows, cols = 6, 14
spots = [Rectangle((c * 1.1, r * 2.2), 1, 2) for r in range(rows) for c in range(cols)]
hours = rng.gamma(2.0, 1.6, rows * cols)
hours[rng.random(rows * cols) < 0.2] = np.nan # empty spaces
collection = PatchCollection(spots, cmap="YlOrRd", edgecolor="white", linewidth=1)
collection.set_array(np.ma.masked_invalid(hours))
fig, ax = plt.subplots(figsize=(10, 4.6))
ax.add_collection(collection)
ax.autoscale_view()
ax.set_aspect("equal")
ax.axis("off")
fig.colorbar(collection, ax=ax, label="Hours parked", shrink=0.8)
plt.show()

Use ax.add_collection rather than add_patch, and set_array supplies the numbers the colormap turns into colors. Masked values are drawn with the colormap's "bad" color, which is transparent by default, so the empty spaces show as blank gaps.
Can't Reuse a Patch on a Second Axes
A patch belongs to one axes. Adding the same object to another raises an error, so build a fresh patch for each axes, or write a small function that returns one:
def badge():
return Circle((0.5, 0.5), 0.3, facecolor="#e76f51")
shared = badge()
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.add_patch(shared)
try:
ax2.add_patch(shared)
except ValueError as err:
print(err)
ax2.add_patch(badge()) # a new object works
Can not reset the Axes. You are probably trying to reuse an artist in more than one Axes which is not supported
Which Approach Should I Use?
| You want | Use |
|---|---|
| One or a few shapes on a chart | ax.add_patch(Rectangle(...)), Circle, Ellipse, Polygon |
| A band across the whole plot | ax.axvspan or ax.axhspan |
| A line between two points | ax.plot or ax.hlines / ax.vlines |
| An arrow or callout | ax.annotate, FancyArrowPatch |
| Hundreds of similar shapes | PatchCollection and ax.add_collection |
| A shape that stays put when you zoom | transform=ax.transAxes |
Practical Tips
- Set limits yourself. Call
ax.autoscale_view()orset_xlim/set_ylimafter adding patches to a fresh axes, because patches alone don't resize it. - Use
set_aspect("equal")for round circles. Otherwise aCirclefollows the x and y scales and can look like an oval. - Name the anchor.
Rectangle((x, y), w, h)anchors at the lower-left corner andEllipseandCircleat the center. Mixing them up is the most common reason shapes land in the wrong place. - Use
zorderto layer. A translucentRectangleon top of a scatter needs a higherzorderthan the points, or the points sit above the fill. - Add legend entries by hand. Patches drawn with
add_patcharen't in the legend unless you passlabel=. The legend post shows how to build custom handles.