Read images and insert as subplots

Question:

I have created 6 png plots with different python scripts.

Example of plots created by the same script:

import numpy as np
import matplotlib.pyplot as plt

plot_num=6
for num in np.arange(plot_num):
    fig, ax = plt.subplots()
    x=np.arange(10)
    y=np.random.rand(10,)
    plt.plot(x,y, marker='o',mfc='red')
    plt.savefig('plot_'+str(num)+'.png')

I would like to read the saved plots in and produce a single common figure of 3 (columns) * 2 (rows).

What is the best solution to do that?

The following code shows approximately what I want, but it displays additional axes and I don’t know how to adjust the vertical and horizontal distance between plots.

import matplotlib.pyplot as plt
from PIL import Image
from IPython.display import Image, display

fig,ax = plt.subplots(2,3)

filenames=['plot_{}.png'.format(i) for i in range(6)] 

for i in range(6):
    with open(filenames[i],'rb') as f:
        image=Image.open(f)
        ax[i%2][i//2].imshow(image)

display(fig)

enter image description here

Asked By: len

||

Answers:

Matplotlibs subplot functions might be just your taste. However, they’re used on creation as far as I know.

Edit: Re-reading your question: Would it be possible to use your other python scripts as libraries for that one script, then adding each individual script as a subplot?

Answered By: MrBlueCharon
import matplotlib.pyplot as plt

my_dpi=300
fig, ax = plt.subplots(nrows=2, ncols=3, figsize=(4,2), dpi=my_dpi)

plt.subplots_adjust(left=0.01,
                bottom=0.1,
                right=0.9,
                top=0.9,
                wspace=0,
                hspace=-0.3)

filenames=['plot_{}.png'.format(i) for i in range(6)] 

for i in range(6):
    with open(filenames[i],'rb') as f:
        image=plt.imread(f)
        ax[i%2][i//2].axis('off')
        ax[i%2][i//2].imshow(image)

enter image description here

Answered By: len
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.