6

I created two functions that make two specific plots and returns me the respective figures:

import matplotlib.pyplot as plt

x = range(1,100)
y = range(1,100)

def my_plot_1(x,y):
    fig = plt.plot(x,y)
    return fig

def my_plot_2(x,y):
    fig = plt.plot(x,y)
    return fig

Now, outside of my functions, I want to create a figure with two subplots and add my function figures to it. Something like this:

my_fig_1 = my_plot_1(x,y)
my_fig_2 = my_plot_2(x,y)

fig, fig_axes = plt.subplots(ncols=2, nrows=1)
fig_axes[0,0] = my_fig_1
fig_axes[0,1] = my_fig_2

However, just allocating the created figures to this new figure does not work. The function calls the figure, but it is not allocated in the subplot. Is there a way to place my function figure in another figure's subplot?

2
  • Probably better to pass an Axes to your function: def my_plot_1(x, y, ax):, ax.plot(x, y)
    – BigBen
    Jan 7, 2021 at 18:33
  • Could you expand on this? How would I use this Axes later in the main figure? My original function uses Axes, but I would like to send everything to the main figure. My function also modifies font size and other things, and I wanted to keep everything in the main figure. Jan 7, 2021 at 18:48

1 Answer 1

9

Eaiser and better to just pass your function an Axes:

def my_plot_1(x, y, ax):
    ax.plot(x, y)

def my_plot_2(x, y, ax):
    ax.plot(x, y)

fig, axs = plt.subplots(ncols=2, nrows=1)

# pass the Axes you created above
my_plot_1(x, y, axs[0])
my_plot_2(x, y, axs[1])
2
  • I'm finding a small problem. One of my functions create a figure with a colorbar. I'm not able to carry this colorbar with me, since there is no figure. The following error occurs No mappable was found to use for colorbar creation. First define a mappable such as an image (with imshow) or a contour set (with contourf). Any thoughts? Jan 7, 2021 at 19:29
  • It may make more sense to ask that as a new question with a relevant code snippet, so that we can provide the best answer.
    – BigBen
    Jan 7, 2021 at 19:31

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.