'How to add_subplot figure generated from external function with matplotlib

Currently, I have THREE function to create the graphic, namely get_image_1, get_image_2, and get_image_3 as shown in the function below.

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

For simplicity, we just use simple plt.plot().

The above function are called via

get_image_1()
get_image_2()
get_image_3()

I would like to display these THREE plot as shown in this figure.

enter image description here

Currently, I had to save each of the image locally. For example in the function get_image_1, notice the line fig.savefig('image_1.png').

and re-upload the saved images and subsequently combine them as per the code below

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()

I wonder how to do this activity more efficiently. Such that, to skip entirely the saved and re-upload the image.



Solution 1:[1]

As per @BigBen suggestion in the comment.

Modify the function to accept axes parameter

  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])

Then, pass the axes parameter for each function calling

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()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1