I am trying to write a Python function that displays a grid of images in full screen mode using pyplot. When the window opens (TkAgg interactive backend on Windows 10), part of my plot is off the screen as seen here:
This is how it should look like:
How can I make the figure appear correctly on the screen?
Here is my code:
from PIL import Image
import matplotlib.pyplot as plt
def imageGrid(data_obj, grid=(3,3), start_idx=0):
# set figure size to 1 inch by 1 inch
figure = plt.figure(figsize=(1,1))
cols, rows = grid
idx = start_idx
for i in range(1, cols * rows + 1):
img = data_obj[idx]
figure.add_subplot(rows, cols, i)
plt.axis("off")
plt.imshow(img, cmap="gray")
idx += 1
plt.subplots_adjust(wspace=0, hspace=0, left=0, right=1, bottom=0, top=1)
# make the window open in full screen (this line is breaking it)
plt.get_current_fig_manager().window.state('zoomed')
plt.show()
list_of_images = [Image.open("Screenshot 2023-08-30 170601.png") for i in range(9)]
imageGrid(list_of_images)
To make the window appear full screen, I followed the instructions described here and here.
I have tried making the figure smaller by setting the figure to 1 by 1 inch, which is definitely smaller than my screen, but no matter what I set it seems to have no effect.
If I manually resize the window (take it in and out of full screen mode) after it opened the problem is resolved, so I was able to capture the desired look.
This seems to be a bug in matplotlib, but I have found a way to display it correctly for the first time the window opens. Note however, that once the window is resized by hand, this will "overcorrect" and the result will not be the same. Here are the steps:
plt.subplots_adjust
with the values obtained aboveI ended up changing the line
plt.subplots_adjust(wspace=0, hspace=0, left=0, right=1, bottom=0, top=1)
to plt.subplots_adjust(wspace=0, hspace=0, left=0, right=0.565, bottom=0.442, top=1)
, so the final code is:
from PIL import Image
import matplotlib.pyplot as plt
def imageGrid(data_obj, grid=(3,3), start_idx=0):
# set figure size to 1 inch by 1 inch
figure = plt.figure(figsize=(1,1))
cols, rows = grid
idx = start_idx
for i in range(1, cols * rows + 1):
img = data_obj[idx]
figure.add_subplot(rows, cols, i)
plt.axis("off")
plt.imshow(img, cmap="gray")
idx += 1
plt.subplots_adjust(wspace=0, hspace=0, left=0, right=0.565, bottom=0.442, top=1)
# make the window open in full screen (this line is breaking it)
plt.get_current_fig_manager().window.state('zoomed')
plt.show()
list_of_images = [Image.open("Screenshot 2023-08-30 170601.png") for i in range(9)]
imageGrid(list_of_images)