Note: This is different from the following questions which make the following assumptions:
- pyplot - copy an axes content and show it in a new figure: Deletes lines from an axis
- Plot something in one figure, and use it again later for another figure: code to plot the lines again is available
- matplotlib - duplicate plot from one figure to another?: moves onto a new empty figure
Here instead, the goal is to add lines to an existing axis which already has other lines on it.
I want to merge two axes that have been created as follows:
xx = np.arange(12)
fig1, ax1 = plt.subplots()
ax1.plot(xx, np.sin(xx), label="V1")
fig2, ax2 = plt.subplots()
ax2.plot(xx, 0*xx, label="V2")
Suppose I no longer have access to the code used to create these plots, but just to fig1, ax1, fig2, ax2
objects (e.g. via pickling).
The two plots should be merged such that the output is (visually) the same (up to colors) as the output of:
fig, ax = plt.subplots()
ax.plot(xx, np.sin(xx), label="V1")
ax.plot(xx, 0*xx, label="V2")
I have tried
# move lines from ax1 to ax2
def move_lines_to_axis(ax1, ax2):
for line in ax1.lines:
line.remove()
line.set_linestyle("dashed")
line.recache(always=True)
ax2.add_line(line)
return ax2
ax2 = move_lines_to_axis(ax1, ax2)
ax2.figure
but this gives the wrong scaling.
How can I copy the lines from one figure to the other?
Fig1:
Fig2:
Expected merged figure:
What the above code gives (note the wrong y-scale of the sinus):
This seems to be related to the axis transformation, but looking at the code of
add_line
, it sets the transformation to ax.transData
.