有没有办法创建一个子图,其中包含在函数内部创建的图?

Is there a way to create a subplot that contains plots created inside functions?

我想创建一个有 4 个数字的子图。但是,我的图是在函数中创建的....例如:

def random(x):
    variable_x = x
    result = f(x)
    plt.plot(result, x)
    plt.show()

random(x)

我有四个用于不同目的的函数,但我想在同一个子图中使用所有四个图。这可能吗?谢谢。

如果你创建函数 "single responsibility" 并让它 return 结果并从外部进行绘图,你会让自己的生活变得更轻松:

def random(x):
    variable_x = x
    return result = f(x)

result = random(x)
plt.plot(result, x)
plt.show()

您还可以更轻松地测试这些。
如果你确定要在里面画图,可以传入一个plot函数:

def random(x, show):
    variable_x = x
    result = f(x)
    show(result)

def show(result):
    plt.plot(result, x)
    plt.show()

result = random(x, show)

这将允许您控制哪个函数显示在哪里。