5

I'm trying to have an imshow plot inset into another in matplotlib.

I have a figure that has an plot on top and an imshow on the bottom:

fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
plt.plot()
ax2 = fig.add_subplot(2,1,2)
plt.imshow()

and then I have another figure, which also is comprised of a plot on top and an imshow below. I want this second figure to be inset into the top plot on the first figure.

I tried follow this example. The code ran without an error but I had an empty axis in the position I wanted it.

My problem is just that I'm not sure where to put the plt.setp() command If that's what I am supposed to use.

1 Answer 1

7

First, I don't think you can put a figure into a figure in matplotlib. You will have to arrange your Axes objects (subplots) to achieve the look you want.

The example you provided uses absolute positioning to do that. setp there is not related to positioning, though — it just removes axis ticks from insets. An example of code that does what you want:

import numpy
import matplotlib.pyplot as plt

x = numpy.linspace(0, 1)

xx, yy = numpy.meshgrid(x, x)
im = numpy.sin(xx) + numpy.cos(yy)**2


fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(x, x**2)
ax2 = fig.add_subplot(2,1,2)
ax2.imshow(im)

inset1 = fig.add_axes([.15, .72, .15, .15])
inset1.plot(x, x**2)
plt.setp(inset1, xticks=[], yticks=[])

inset2 = fig.add_axes([0.15, 0.55, .15, .15])
inset2.imshow(im)
plt.setp(inset2, xticks=[], yticks=[])

fig.savefig('tt.png')

enter image description here

Here the insets use explicit positioning with coordinates given in "figure units" (the whole figure has size 1 by 1).

Now, of course, there's plenty of room for improvement. You probably want the widths of your plots to be equal, so you'll have to:

  • specify the positioning of all subplots explicitly; or
  • play with aspect ratios; or
  • use two GridSpec objects (this way you'll have the least amount of magic numbers and manual adjustment)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.