2

I would like to define two figures objects and then in a loop I would like to contribute to each of them. The following code will not work but it demonstrate how it works.

import matplotlib.pyplot as plt

plt1.figure()
plt1.xticks(rotation=90)

plt2.figure()
plt2.xticks(rotation=90)

for i in range(5):

   plt1.plot(xs_a[i], ys_a[i], label='line' + str(i))
   plt2.plot(xs_b[i], ys_b[i], label='line' + str(i))

plt1.savefig(fname_1)
plt2.savefig(fname_2)

I always perceived plt as an image object for which I can set some parameters (for example xticks) or to which I can add some curves. However, plt is a library that I import. So, what I should do when I need to define two or more figure objects?

Roman
  • 124,451
  • 167
  • 349
  • 456
  • 1
    Check out this similar question: http://stackoverflow.com/questions/6916978/how-do-i-tell-matplotlib-to-create-a-second-new-plot-then-later-plot-on-the-o. I think the gist is that you can use something like fig1=plt.figure() and fig2=plt.figure() then use fig1 and fig2. – TravisJ Apr 21 '15 at 12:37

1 Answers1

4

This should work. You first create two figure objects (fig1and fig2). For each of the figures, you add axes using the add_subplot method. Then, you can use these axes objects to plot whatever you want and set the parameters to your need (like the ticks).

import matplotlib.pyplot as plt

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

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

for i in range(5):

    ax1.plot(xs_a[i], ys_a[i], label='line' + str(i))
    ax2.plot(xs_b[i], ys_b[i], label='line' + str(i))

plt.setp( ax1.xaxis.get_majorticklabels(), rotation=90)
plt.setp( ax2.xaxis.get_majorticklabels(), rotation=90)

fig1.savefig(fname_1)
fig2.savefig(fname_2)
Julien Spronck
  • 15,069
  • 4
  • 47
  • 55