Combine two pyplot axis into single axis

156 Views Asked by At

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.

0

There are 0 best solutions below