1

I've got a series of functions that return three plot objects (figure, axis and plot) and I would like to combine them into a single figure as subplots. I've put together example code:

import matplotlib.pyplot as plt
import numpy as np

def main():

    line_fig,line_axes,line_plot=line_grapher()
    cont_fig,cont_axes,cont_plot=cont_grapher()

    compound_fig=plot_compounder(line_fig,cont_fig)#which arguments?

    plt.show()

def line_grapher():
    x=np.linspace(0,2*np.pi)
    y=np.sin(x)/(x+1)

    line_fig=plt.figure()
    line_axes=line_fig.add_axes([0.1,0.1,0.8,0.8])
    line_plot=line_axes.plot(x,y)
    return line_fig,line_axes,line_plot

def cont_grapher():
    z=np.random.rand(10,10)

    cont_fig=plt.figure()
    cont_axes=cont_fig.add_axes([0.1,0.1,0.8,0.8])
    cont_plot=cont_axes.contourf(z)
    return cont_fig,cont_axes,cont_plot

def plot_compounder(fig1,fig2):
    #... lines that will compound the two figures that
    #... were passed to the function and return a single
    #... figure
    fig3=None#provisional, so that the code runs
    return fig3

if __name__=='__main__':
    main()

It would be really useful to combine a set of graphs into one with a function. Has anybody done this before?

1 Answer 1

1

If you're going to be plotting your graphs on the same figure anyway, there's no need to create a figure for each plot. Changing your plotting functions to just return the axes, you can instantiate a figure with two subplots and add an axes to each subplot:

def line_grapher(ax):
    x=np.linspace(0,2*np.pi)
    y=np.sin(x)/(x+1)

    ax.plot(x,y)


def cont_grapher(ax):
    z=np.random.rand(10,10)

    cont_plot = ax.contourf(z)

def main():

    fig3, axarr = plt.subplots(2)
    line_grapher(axarr[0])
    cont_grapher(axarr[1])

    plt.show()


if __name__=='__main__':
    main()

Look into the plt.subplots function and the add_subplot figure method for plotting multiple plots on one figure.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, the thing is, I can't pass the axis as an argument to the function, and my plotting functions return those three objects every time. I've tried: axarr[0] = line_grapher()[1]; axarr[1]=cont_grapher()[1] But I get three figures.
If your functions are calling plt.figure then they will create their figures. Why do your functions need to return those three objects?
I'm working with two functions that are already existing and take a number of arguments to create bespoke figures. I can't modify these with what I'm doing, so I can't pass an axis as an argument.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.