我有一系列函数返回三个绘图对象(图形,轴和图),我想将它们组合成一个单独的图形作为子图。我已将示例代码放在一起:
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()
将一组图表合并为一个函数非常有用。有没有人这样做过?
答案 0 :(得分:1)
如果你打算在同一个数字上绘制图表,那么就不需要为每个情节创建一个数字。将绘图函数更改为仅返回轴,可以实例化带有两个子图的图形,并为每个子图添加一个轴:
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()
查看plt.subplots
函数和add_subplot
数字方法,在一个数字上绘制多个图。