Insets
You can create axes that sit inside other axes. You can come across examples of axes that display magnified portions of the main axis. We call such axes insets. We use the add_axes method to create them. Here’s a graph without any insets:
In [1]:
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-10, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y, color='g')
Out[1]:
Let’s first rewrite the code so that we create a figure on its own and then add the axis. The axis is going to fill the whole figure:
In [11]:
fig = plt.figure()
x = np.linspace(-10, 10, 100)
y = np.sin(x)
ax = fig.add_axes((0, 0, 1, 1))
ax.plot(x, y, color='g')
Out[11]:
And now suppose we want to add an inset with the magnified portion of the above axis which is between x1 = -6 and x2 = -4. Here’s the code:
In [19]:
# MAIN AXIS
fig = plt.figure()
x = np.linspace(-10, 10, 100)
y = np.sin(x)
ax = fig.add_axes((0, 0, 1, 1))
ax.plot(x, y, color='g')
# INSET
# Let's define x1 and x2.
x1, x2 = -6, -4
# Let's create the inset in the upper right quarter of the main axis.
ax_inset = fig.add_axes((.6, .6, .35, .35))
# Here are the x and y values for the inset.
inset_x = np.linspace(x1, x2, 100)
inset_y = np.sin(inset_x)
# Let's plot the inset.
ax_inset.plot(inset_x, inset_y, color='g')
Out[19]:
If you want, you can add as many insets as you need. You can also add vertical lines to the main axis to clearly show which area is magnified in the inset. To this end you can use the axvline method:
In [22]:
# MAIN AXIS
fig = plt.figure()
x = np.linspace(-10, 10, 100)
y = np.sin(x)
ax = fig.add_axes((0, 0, 1, 1))
ax.plot(x, y, color='g')
# INSET
x1, x2 = -6, -4
# Let's add dotted vertical lines at x1 and x2.
ax.axvline(x1, linestyle=':')
ax.axvline(x2, linestyle=':')
ax_inset = fig.add_axes((.6, .6, .35, .35))
inset_x = np.linspace(x1, x2, 100)
inset_y = np.sin(inset_x)
ax_inset.plot(inset_x, inset_y, color='g')
Out[22]: