Skip to content
Home » matplotlib Part 15 – Insets

matplotlib Part 15 – Insets

Spread the love

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]:
[<matplotlib.lines.Line2D at 0x19834b0eb88>]

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]:
[<matplotlib.lines.Line2D at 0x198352b5c88>]

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]:
[<matplotlib.lines.Line2D at 0x198367eae08>]

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]:
[<matplotlib.lines.Line2D at 0x19836a6c848>]

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply