12

I checked this SO Matplotlib returning a plot object but it does not really fit to my question.

What I would like to do is:

def func1():
   fig1 =  plt.plot (np.arange(0.0, 5.0, 0.1))
   return fig1

def func2()
   return plt.plot (np.arange(0.0, 5.0, 0.02))


fig1 = func1()
fig2 = func2()
plt.figure()
plt.add_subplot(fig1)
plt.add_subplot(fig2)
plt.show()

The above code is just a main idea. Could you suggest me how to do?

Thanks

mommomonthewind
  • 4,390
  • 11
  • 46
  • 74
  • rather than returning something like `fig` object you might consider passing `Axis` to your plotting functions instead. – taras Aug 28 '18 at 09:35

1 Answers1

13

The idea would be to let your functions plot to an axes. Either you provide this axes as argument to the function or you let it take the current axes.

import matplotlib.pyplot as plt
import numpy as np

def func1(ax=None):
    ax = ax or plt.gca()
    line, = ax.plot (np.arange(0.0, 5.0, 0.1))
    return line

def func2(ax=None):
    ax = ax or plt.gca()
    line, = ax.plot (np.arange(0.0, 5.0, 0.02))
    return line


fig, (ax1,ax2) = plt.subplots(ncols=2)
func1(ax1)
func2(ax2)

plt.show()
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • So the other way around is impossible? – MasterScrat May 09 '19 at 17:37
  • @MasterScrat No, very little is impossible. But matplotlib is not designed to have artists copied between figures. So any other solution becomes utterly complicated (and is unsupported). See [this answer](https://stackoverflow.com/a/46906599/4124317) for the principle - which might already not work anymore by now. – ImportanceOfBeingErnest May 09 '19 at 18:47