J.B. Brown
J.B. Brown

Reputation: 1823

Merge two matplotlib figure.Figure or axes.Axes objects into a new one

I have an external function which returns a Figure object, and in this situation, each Figure object is composed of exactly one Axes object.
I want to compose a new figure consisting of these two figures (let's say horizontal joining).
So ideally, I would like to say:

fig1, fig2, joined = CreateFig( data1 ), CreateFig( data2 ), Figure()
subp1, subp2 = joined.add_subplot( 121 ), joined.add_subplot( 122 )
subp1, subp2 = fig1.get_axes()[0], fig2.get_axes()[0]
joinedFig.savefig( 'joined.eps' )

Obviously, this doesn't work, as the axes retrieved belong to fig1 and fig2, not joinedFig.
The axes also cannot be merely duplicated by copy.deepcopy().

In my example, I am referring to figure.Figure() instantiation. While a search did lead me to see that pyplot.figure() is the development team's recommended instantiation technique, it doesn't change the question: is there any way to do Axes/Figure copy construction and Figure construction via composition of copied Axes?

Upvotes: 3

Views: 6934

Answers (1)

unutbu
unutbu

Reputation: 879361

Can you modify CreateFig? If so, there is an easy solution: create the desired figure and axes first, then pass the axes to CreateFig, and let CreateFig manipulate the axes object:

import matplotlib.pyplot as plt
import numpy as np

def CreateFig(data, ax):
    ax.plot(data)

fig, axs = plt.subplots(1, 2)
data = np.sin(np.linspace(0,2*np.pi,100))
CreateFig(data, axs[0])
data = np.linspace(-2,2,100)**2
CreateFig(data, axs[1])
plt.show()

enter image description here

Upvotes: 3

Related Questions