将函数中创建的图窗添加到另一个图窗的子图中

Luc*_*ira 7 python graph matplotlib figure subplot

我创建了两个函数来绘制两个特定的图并返回各自的数字:

import matplotlib.pyplot as plt

x = range(1,100)
y = range(1,100)

def my_plot_1(x,y):
    fig = plt.plot(x,y)
    return fig

def my_plot_2(x,y):
    fig = plt.plot(x,y)
    return fig
Run Code Online (Sandbox Code Playgroud)

现在,在我的函数之外,我想创建一个带有两个子图的图形并将我的函数图形添加到其中。像这样的东西:

my_fig_1 = my_plot_1(x,y)
my_fig_2 = my_plot_2(x,y)

fig, fig_axes = plt.subplots(ncols=2, nrows=1)
fig_axes[0,0] = my_fig_1
fig_axes[0,1] = my_fig_2
Run Code Online (Sandbox Code Playgroud)

然而,仅仅将创建的图形分配给这个新图形是行不通的。该函数调用该图窗,但未在子图中分配该图窗。有没有办法将我的函数图放置在另一个图的子图中?

Big*_*Ben 9

更容易更好地传递你的函数Axes

def my_plot_1(x, y, ax):
    ax.plot(x, y)

def my_plot_2(x, y, ax):
    ax.plot(x, y)

fig, axs = plt.subplots(ncols=2, nrows=1)

# pass the Axes you created above
my_plot_1(x, y, axs[0])
my_plot_2(x, y, axs[1])
Run Code Online (Sandbox Code Playgroud)