1

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?

user
  • 2,015
  • 6
  • 22
  • 39
  • You need to show us how you draw the plots. Also, the objects you call fig1 and fig2 are not `Figure`s but `Axes` so it's a bit confusing. – Guimoute Apr 05 '20 at 18:56

1 Answers1

1

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.

Guimoute
  • 4,407
  • 3
  • 12
  • 28
  • I am dealing with hundreds of functions and I am trying to find a way to achieve this without having to rewrite all the code. – user Apr 05 '20 at 19:22
  • If they all look the same, I'm sure we can compact those hundreds of functions down to one with a few parameters... but we can't help you further if you don't show us an example. Do you have one subplot per function or always 2? – Guimoute Apr 05 '20 at 19:26
  • I understand, not sure I can share the code now, but thank you. My question is: if for each plot I have the plt.gcf(), is it possible to use it so that I can pass it in fig, (fig1,fig2) = plt.subplots(ncols=2) and draw those plots as subplots of a figure? – user Apr 05 '20 at 19:39
  • From what I understood, you have only one figure (it's `fig`) on which you create subplots, so `return plt.gcf()` does not provide any information because it always returns the same figure (`fig`!)... *Unless* you do something with figures in the part of the code that you cannot share. – Guimoute Apr 05 '20 at 19:45
  • What I am saying is I have two functions, they return fig1 and fig2. They are different, I can save them and they work. That part is fine. Now, I want to create a new figure that has fig1 and fig2 as subplots. – user Apr 05 '20 at 20:28