3

I am new to matplotlib and am trying to get my head around how to add figures to a subplot.

I have three different functions, which output a single figure:

def plot_fig_1(vars, args):
    f, ax, put.subplots()
    # do something
    ax.plot(x, y)
    return f, ax


def plot_fig_2(vars, args):
    f, ax, put.subplots()
    # do something
    ax.plot(x, y)
    return f, ax

Now, for example I would like to merge both figures into a single plot with shared X axis. I tried:

f_1, ax_1 = plot_fig_1(...)
f_2, ax_2 = plot_fig_2(...)

new_fig, new_ax = plt.subplots(2,1)
new_ax[0] = f_1
new_ax[1] = f_2

and here I am basically lost. I'm reading the Matplotlib manual, but no luck so far.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Arnold Klein
  • 2,956
  • 10
  • 31
  • 60
  • 1
    I need to ad FIGURES to a subplot. I created two figures, and want to merge them in a single plot. I tried your method, but it does not work. Thanks. – Arnold Klein May 10 '18 at 18:35
  • You mean like in [this question](https://stackoverflow.com/q/16748577/8881141)? – Mr. T May 10 '18 at 18:40
  • 2
    Just to make sure we're on the same line here: You cannot add a figure to another figure or to anything inside another figure. Just as you cannot add an oven to an oven. Instead of adding a pizza in each of two ovens and trying to put both ovens into another oven, the solution is of course to put both pizza into the same oven. – ImportanceOfBeingErnest May 10 '18 at 19:52
  • I don't understand that response. You can take a picture of two pictures and then you have a picture containing both. I seems to be that figures can't be hierarchically nested in matplotlib, which is what we would need here. This ends up being an issue for example when using facetgrid plots in seaborn. They can't easily be placed as a subplot within a larger figure, as far as i can see. – Jim Sep 24 '20 at 18:42

1 Answers1

2

Unless your function signatures have to stay as they are defined in your example it would be easier to create the subplots outside of the functions and pass the appropriate Axes instance to each function.

def plot_fig_1(vars, args, ax):
    # do something
    ax.plot(x, y)

def plot_fig_2(vars, args, ax):
    # do something
    ax.plot(x, y)

fig, ax = plt.subplots(2, 1, sharex=True)
plot_fig_1(..., ax[0])
plot_fig_2(..., ax[1])

If you needed to create a figure containing just one of the subplots you can do so with:

fig, ax = plt.subplot()
plot_fig_1(..., ax)

Or, if the functions need to be self-contained, give the ax argument a default value and test for it inside the function.

def plot_fig_1(vars, args, ax=None):
    if ax is None:
        fig, ax = plt.subplot()
    # do something
    ax.plot(x, y)
mostlyoxygen
  • 981
  • 5
  • 14