简体   繁体   English

来自绘图对象的matplotlib子图

[英]matplotlib subplots from plot objects

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? 有人做过吗?

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. 查看plt.subplots函数和add_subplot图形方法,以在一个图形上绘制多个图形。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM