Matplotlib: plotting the same plot on two different figures without specifying the line "plot (x, y)" twice

I have this simple code that depicts the same thing in two different shapes (Figure 1 and Figure 2). However, I have to write the line ax.plot (x, y) twice, once for ax1 and once for ax2. How can I only use one expression in the plot (with multiple unreadable ones could be a source of problems for my more complex code). Something like ax1, ax2.plot (x, y) ...?

import numpy as np
import matplotlib.pyplot as plt

#Prepares the data
x = np.arange(5)
y = np.exp(x)

#plot fig1
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)

#plot fig2
fig2 = plt.figure()
ax2 = fig2.add_subplot(111)

#adds the same fig2 plot on fig1
ax1.plot(x, y)
ax2.plot(x, y)

plt.show()

      

+3


source to share


2 answers


You can either add each axis to the list, for example:

import numpy as np
import matplotlib.pyplot as plt

axes_lst = []    
#Prepares the data
x = np.arange(5)
y = np.exp(x)


#plot fig1
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
axes_lst.append(ax1)

#plot fig2
fig2 = plt.figure()
ax2 = fig2.add_subplot(111)
axes_lst.append(ax2)

for ax in axes_lst:
    ax.plot(x, y)

plt.show()

      



or you can use this unsupported function to pull out all shapes in pyplot. Taken from fooobar.com/questions/149694 / ...

figures=[manager.canvas.figure
         for manager in matplotlib._pylab_helpers.Gcf.get_all_fig_managers()]
for figure in figures:
    figure.gca().plot(x,y)

      

+1


source


Without knowing about matplotlib, you can add all your axes (?) To the list:

to_plot = []
to_plot.append(ax1)
...
to_plot.append(ax2)
...

# apply the same action to each ax
for ax in to_plot: 
    ax.plot(x, y)

      



Then you can add as many as you like and the same will happen with everyone.

+1


source







All Articles