user
user

Reputation: 2103

Aggregating plots from different functions together in matplotlib in python

I have two functions that draw different plots, say foo1 and foo2. I added a return plt.gcf() at the end, so I have:

def foo1():

  #draw plot
  return plt.gcf()

def foo2():

  #draw plot
  return plt.gcf()

I wrote some code that saves those plots:

fig1 = foo1()
fig2 = foo2()

fig1.savefig("tmp1")
fig2.savefig("tmp2")

And it works fine, next I want to do:

fig, (fig1,fig2) = plt.subplots(ncols=2)
fig1 = foo1()
fig2 = foo2()
fig.savefig("tmp")

This is where it fails because I only get two empty plots. Is there any way to modify the last two lines of code to get my two figures to show next to each other (as in plt.subplots(ncols=2)), or at least save them in the same file?

Upvotes: 1

Views: 140

Answers (1)

Guimoute
Guimoute

Reputation: 4629

You do not need to use specific functions or return the current figure. You simply need to specific which ax plots your data and then fig.savefig will work just fine and save both axes because they belong to the same figure.

fig, (ax1, ax2) = plt.subplots(ncols=2)
ax1.plot([1,2,3,4,5], [1,2,3,4,5], color="red")
ax2.plot([1,2,3,4,5], [1,4,9,25,36], color="blue")
fig.savefig("tmp.png")

If you keep the three first lines of that code, you can then take a look here to save the two axes in different files if you wish.

Upvotes: 1

Related Questions