如何使用matplotlib将外部函数生成的图形添加到subplot中

3

目前,我有三个用于创建图形的函数,分别是get_image_1get_image_2get_image_3,如下所示。

def get_image_1():
    fig, ax = plt.subplots(figsize=(8, 6))
    plt.plot(range(10))
    fig.savefig('image_1.png')
    # return fig

def get_image_2():
    fig, ax = plt.subplots(figsize=(8, 6))
    plt.plot([0,5,8,9,3,6])
    fig.savefig('image_2.png')
    # return fig

def get_image_3():
    fig, ax = plt.subplots(figsize=(8, 6))
    plt.plot([100,5,8,9,3,6])
    fig.savefig('image_3.png')
    # return fig

为了简单起见,我们只使用简单的plt.plot()

上述函数是通过以下方式调用的

get_image_1()
get_image_2()
get_image_3()

我想展示这三个图,如图所示。

enter image description here

目前,我必须将每个图像保存在本地。例如,在函数get_image_1中,请注意行fig.savefig('image_1.png')

然后重新上传已保存的图像,并根据以下代码组合它们。

import matplotlib.pyplot as plt
import cv2 as cv
fig = plt.figure(figsize=(9, 10))
for idx,dpath in enumerate(['image_1.png','image_2.png','image_3.png']):
    tt=1
    if idx!=2:
        sub1 = fig.add_subplot(2, 2, idx + 1)
    else:
        sub1 = fig.add_subplot(2, 2, (3,4))

    image2 = cv.imread(dpath)
    sub1.imshow(image2, 'gray')

plt.show()

我想知道如何更有效率地完成这个活动,以便完全跳过“已保存”并重新上传图片。

2
不要在 get_image_1get_image_2get_image_3 中创建子图,而是将一个 axes 参数传递给它们。 - BigBen
1个回答

1
根据评论中@BigBen的建议,修改该函数以接受“axes”参数。
  def get_image_1(ax):
    ax.plot(range(10))


def get_image_2(ax):
    ax.plot([0,5,8,9,3,6])

def get_image_3(ax):
    ax.plot([100,5,8,9,3,6])

然后,对于每个function调用,传递axes参数

fig = plt.figure(figsize=(9, 10))

ax1 = fig.add_subplot(2, 2, 1)
get_image_1(ax1)

get_image_2(fig.add_subplot(2, 2, 2))

get_image_3(fig.add_subplot(2, 2, (3,4)))

plt.show()

谢谢@BigBen,我已经相应地更新了答案。 - mpx

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接