Zézouille
Zézouille

Reputation: 533

How to handle multi figures with matplotlib in a for loop

I want to plot different things in two different figures in only 1 loop (I have a huge matrice that I don't want to put 2 for loops) like the following:

plt.figure(0)
plt.figure(1)
for i in range(10):
   #plot it only on the figure(0)
   plt.plot(np.arange(10), np.power(np.arange(10), i), label = 'square') 
   #plot it only on the figure(1)
   plt.plot(np.arange(10), np.power(np.arange(10), 1/i), label = '1/square') 
   plt.legend() #if it does for both figures seperately
plt.show()

How can I achieve this? Thanks a lot.

Upvotes: 0

Views: 826

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339765

Using the pyplot state-like interface

You would need to "activate" the respective figure before plotting to it.

plt.figure(0)
plt.figure(1)

for i in range(10):
   #plot it only on the figure(0)
   plt.figure(0)
   plt.plot(np.arange(10), np.power(np.arange(10), i), label = 'square') 
   #plot it only on the figure(1)
   plt.figure(1)
   plt.plot(np.arange(10), np.power(np.arange(10), 1/i), label = '1/square')

#legend for figure(0)
plt.figure(0)
plt.legend()
#legend for figure(1)
plt.figure(1)
plt.legend()
plt.show()

Using the object oriented style

Work with the objects and their methods directly.

fig0, ax0 = plt.subplots()
fig1, ax1 = plt.subplots()
for i in range(10):
   #plot it only on the fig0
   ax0.plot(np.arange(10), np.power(np.arange(10), i), label = 'square') 
   #plot it only on the fig1
   ax1.plot(np.arange(10), np.power(np.arange(10), 1/i), label = '1/square') 

ax0.legend()
ax1.legend()
plt.show()

Upvotes: 5

Related Questions