Inserting subfigures

Inserting a small, embedded figure can be helpful in showing a detail of a figure, or more generally, to emphasize a particular part of a graphic. In this recipe, we are going to see how to insert a subfigure into a figure.

How to do it...

matplotlib allows us to create subregions in any part of a figure, and assign a figure to that subregion. In the following example, a subregion is created to show a detail of the curve:

import numpy as np
from matplotlib import pyplot as plt

X = np.linspace(-6, 6, 1024)
Y = np.sinc(X)

X_detail = np.linspace(-3, 3, 1024)
Y_detail = np.sinc(X_detail)

plt.plot(X, Y, c = 'k')

sub_axes = plt.axes([.6, .6, .25, .25])
sub_axes.plot(X_detail, Y_detail, c = 'k')
plt.setp(sub_axes)

plt.show()

The subregion ...

Get matplotlib Plotting Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.