0

I have a function that returns a fig, ax pair. However I want to put that result inside a subplot of my gridspec.

fig, ax = draw_football_field(dimensions, size) # this is the output that I want to copy to another subplot

fig = plt.figure(constrained_layout=True)
gs = fig.add_gridspec(18, 9)
ax = fig.add_subplot(gs[3:6, 1:3], zorder=1) #this is the target subplot

Any idea on how to do this?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
vftw
  • 1,547
  • 3
  • 22
  • 51

1 Answers1

0

It's non-trivial to pass an Axes object created on one Figure to a different instance of a Figure object as Axes are designed to live on one specific Figure instance. See this SO answer.

I would recommend changing your draw_footlball_field function to accept an Axes object.

def draw_football_field(axes, other_args):
    axes.plot(other_args)
    return axes

Now you can do something along the lines of:

fig = plt.figure(constrained_layout=True)
gs = fig.add_gridspec(18, 9)
ax = fig.add_subplot(gs[3:6, 1:3], zorder=1) #this is the target subplot
ax = draw_football_field(ax, other_args) # modify axes instance from 'this' fig
Jason
  • 4,346
  • 10
  • 49
  • 75