将在函数中创建的图形添加到另一个图形的子图中 [英] Adding a figure created in a function to another figure's subplot

查看:63
本文介绍了将在函数中创建的图形添加到另一个图形的子图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了两个函数,可以绘制两个特定的图并返回各自的图形:

I created two functions that make two specific plots and returns me the respective figures:

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

现在,在我的功能之外,我想创建一个具有两个子图的图形并将其添加到我的功能图形中.像这样:

Now, outside of my functions, I want to create a figure with two subplots and add my function figures to it. Something like this:

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

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

However, just allocating the created figures to this new figure does not work. The function calls the figure, but it is not allocated in the subplot. Is there a way to place my function figure in another figure's subplot?

推荐答案

Eaiser最好将函数传递给 Axes :

Eaiser and better to just pass your function an Axes:

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

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

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

# pass the Axes you created above
my_plot_1(x, y, fig_axes[0])
my_plot_2(x, y, fig_axes[1])

这篇关于将在函数中创建的图形添加到另一个图形的子图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆