Nobody
Nobody

Reputation: 189

How to overlay one pyplot figure on another

Searching easily reveals how to plot multiple charts on one figure, whether using the same plotting axes, a second y axis or subplots. Much harder to uncover is how to overlay one figure onto another, something like this:

Multiple figures overlaid onto another figure

That image was prepared using a bitmap editor to overlay the images. I have no difficulty creating the individual plots, but cannot figure out how to combine them. I expect a single line of code will suffice, but what is it? Here is how I imagine it:

    bigFig = plt.figure(1, figsize=[5,25])
    ...
    ltlFig = plt.figure(2)
    ...
    bigFig.overlay(ltlFig, pos=[x,y], size=[1,1])

I've established that I can use figure.add_axes, but it is quite challenging getting the position of the overlaid plot correct, since the parameters are fractions, not x,y values from the first plot. It also [it seems to me - am I wrong?] places constraints on the order in which the charts are plotted, since the main plot must be completed before the other plots are added in turn.

What is the pyplot method that achieves this?

Upvotes: 3

Views: 5515

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339765

To create an inset axes you may use mpl_toolkits.axes_grid1.inset_locator.inset_axes.

Position of inset axes in axes coordinates

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes

fig, ax= plt.subplots()

inset_axes = inset_axes(ax,
                    width=1,                     # inch
                    height=1,                    # inch
                    bbox_transform=ax.transAxes, # relative axes coordinates
                    bbox_to_anchor=(0.5,0.5),    # relative axes coordinates
                    loc=3)                       # loc=lower left corner

ax.axis([0,500,-.1,.1])
plt.show()

Position of inset axes in data coordinates

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes

fig, ax= plt.subplots()

inset_axes = inset_axes(ax,
                    width=1,                     # inch
                    height=1,                    # inch
                    bbox_transform=ax.transData, # data coordinates
                    bbox_to_anchor=(250,0.0),    # data coordinates
                    loc=3)                       # loc=lower left corner

ax.axis([0,500,-.1,.1])
plt.show()

Both of the above produce the same plot

enter image description here

(For a possible drawback of this solution see specific location for inset axes)

Upvotes: 5

Related Questions