Arnold Klein
Arnold Klein

Reputation: 3086

Adding figures to subplots

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.

Upvotes: 3

Views: 10436

Answers (1)

mostlyoxygen
mostlyoxygen

Reputation: 991

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)

Upvotes: 2

Related Questions