How to overlay one pyplot figure on another

大城市里の小女人 提交于 2021-02-10 12:07:46

问题


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:

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?


回答1:


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

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



来源:https://stackoverflow.com/questions/49065521/how-to-overlay-one-pyplot-figure-on-another

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!