1

Note: This is different from the following questions which make the following assumptions:

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: enter image description here Fig2: enter image description here Expected merged figure: enter image description here What the above code gives (note the wrong y-scale of the sinus): enter image description here This seems to be related to the axis transformation, but looking at the code of add_line, it sets the transformation to ax.transData.

Maximilian Mordig
  • 1,333
  • 1
  • 12
  • 16
  • You need `fig1, (ax1, ax2) = plt.subplots(ncols=2, nrows=1)` and then plot on `ax1` and on `ax2`. Matplotlib doesn't support moving plots created on one `figure` to another `figure`. If you really insist, there exist clumsy workarounds. – JohanC Jan 09 '23 at 19:12
  • I am precisely looking for this workaround. – Maximilian Mordig Jan 09 '23 at 20:06

0 Answers0