part of Course 133 Navigating Matplotlib
import matplotlib.patches as patches path = [[.1, .4], [.2, .9], [.7, .3]] ax.add_patch(patches.Polygon(path))
For me, the biggest reason to use Matplotlib is the unlimited power it gives you over your plots. To fully unlock this power, you need patches. Here's a self-contained example of how to make one.
import matplotlib.patches as patches import matplotlib.pyplot as plt fig = plt.figure() ax = fig.gca() path = [ [.1, .3], [.2, .9], [.8, .4], ] ax.add_patch(patches.Polygon(path)) fig.savefig("patch.png")
Patches are arbitrary two dimensional regions. There are a lot of fancy wrappers and helpers, like Rectangles, Circles, Boxes, and Ellipses, but if you want a single approach that will meet nearly all of your needs, stick with Polygons. They let you define the outline of any two dimensional shape you want, no matter how complex.
Create the path
To initialize a Polygon, it needs a set of points defining its vertices, an outline path. This will need to be in the form of a 2D array with 2 columns, or a similarly shaped list of lists, as we used in the exaple above. No need to repeat the start vertex. By default, the Polygon closes itself.
ax.add_patch(patches.Polygon( path, alpha=.7, edgecolor="darkblue", facecolor="red", hatch="+", joinstyle="miter", linestyle="--", linewidth=5, ))
Patches are customizable in all the typical Matplotlib ways. Go wild.
Heads up: Unilike lines and points, when you add patches to and Axes object, it doesn't automatically change the axis limits to include it. You may have to use ax.set_xlim() and ax.set_ylim() to expand your Axes so that they show the patch. high level functions like plot() and scatter().
I've had to google this more times than I can count. No more!