Reputation: 121
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?
Upvotes: 1
Views: 362
Reputation: 7816
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.
Upvotes: 1