3

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.

1
  • 2
    Instead of creating the subplot within get_image_1, get_image_2, and get_image_3, pass them an axes parameter. Commented May 12, 2022 at 17:01

1 Answer 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()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @BigBen, I have update the answer accordingly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.