The problem is there are 2 seperate Figure
objects displayed on the screen. Each Figure
object contains an Axes
object. How can I overwrite / replace the Axes
object in Figure 1, with the Axes
object from Figure 2?
In other words:
- We have some data called A.
- We plot the data called A.
- The plot is returned in a new Figure and displayed.
- We have some data called B.
- We plot the data called B.
- Now we want to copy and overwrite the
Axes
containing data B into theAxes
containing data A
import matplotlib.pyplot as plt
import numpy as np
plt.ion()
# Draw the first figure and plot
x_1 = np.linspace(0, 10*np.pi, 100)
y_1 = np.sin(x_1)
figure_1 = plt.figure()
axes_1 = figure_1.add_subplot(111)
line_1, = axes_1.plot(x_1, y_1, 'b-')
figure_1.canvas.draw()
# Draw the second figure and plot
x_2 = np.linspace(0, 9*np.pi, 100)
y_2 = np.sin(x_2)
figure_2 = plt.figure()
axes_2 = figure_2.add_subplot(111)
line_2 = axes_2.plot(x_2, y_2, 'r-')
figure_2.canvas.draw()
# Now clear figure_1's axes and replace it with figure_2's axis
figure_1.get_axes()[0].clear()
figure_1.add_axes(axes_2)
figure_1.canvas.draw()
print("Done")
Using the add_axes()
method is raising ValueError "The Axes must have been created in the present figure"
.
Is there a way to detatch the Axes from the current figure so that it can be added to the other one?
There is this question which addresses copying an Axes and displaying in a new figure, however I want to display it in an existing figure.