0

One step in an application I'm writing creates plots to visualize various analyses for users. The methods that create these plots can be called individually, so their outputs are individual fig and ax objects.

One such method basically looks like this:

def make_a_plot(self):
    fig = plt.figure()
    ax = fig.add_subplot(1,1,1)
    
    x = self.x
    y = self.y
    
    ax.plot(x,y)

    return fig, ax

So, if I call this method several times on different objects created by my class, I get fig1, fig2, ax1, ax2.

In another part of the program, I would like to be able to call this method a few times and then display all figures created together in one composite figure. Creating a new figure and adding ax1 and ax2 as separate subplots doesn't seem to work.

I also tried a for loop that gets ax1.lines[i].get_xdata() and ax1.lines[i].get_ydata() and creates new plots from them. But, I can't find a way to access other elements of the figure like vlines and fill_between values. So, that method got me about 50% of the way to the end before I found a wall.

How can I do this? I will gladly erect a shrine on a mountaintop somewhere of anyone who can help me solve this problem :)

Ryan Keeler
  • 41
  • 1
  • 5
  • [Well](https://stackoverflow.com/a/46906599/8881141). – Mr. T Jun 01 '21 at 21:02
  • Quite a few libraries built on top of matplotlib solve this by allowing an `ax` argument to be passed into a function (pandas comes to mind, for example). If it's not specified, a new figure is created - otherwise, the passed-in `ax` is used for plotting. This allows you to control the figure lay-out at the call site, instead of within the function. – Nelewout Jun 01 '21 at 21:09

0 Answers0