0

I am trying to save plots from pyplot as .png using the following code:

import numpy as np
import os
from matplotlib import pyplot as pl

os.chdir("/WORKING/DIRECTORY")

array1 = np.random.rand(10, 3)
array2 = np.random.rand(50, 3)
array3 = np.random.rand(400, 3)

arrays = (array1, array2, array3)
dpi = 300
count = 1

for n in arrays:
    pl.imshow(n, cmap='Accent')
    pl.axis('off')
    pl.savefig(str(count) + ".png", bbox_inches='tight', pad_inches=0, dpi=dpi)
    count +=1

Depending on the array size the results are not as expected. Array1 renders fine. Array2 renders ok, but the last column of values is cut off (a few pixel less wide than the first two columns). Array3 is completely distorted.

Increasing the resolution fixes the problem. I don't want to do that globally as most of my files don't require it. How can I detect the files that are rendered wrong? Pyplot does not return an error eg for array2 or array3. Attached image files for reference.

Any idea how to pick this up as an error or bin the files into a separate folder? Array 1, Array 2, Array3

MarvinO_
  • 1
  • 1
  • Please make a reproducible example of what fails using random data. `np.random.randn` is what I usually use, but it doesn't matter. – Jody Klymak Jan 06 '23 at 20:16
  • Thank you @JodyKlymak. Updated accordingly. – MarvinO_ Jan 08 '23 at 02:22
  • Your aspect ratio makes the width of the image less than 3 pixels at 300 dpi. Make your figure taller if there are so many elements in the vertical. – Jody Klymak Jan 09 '23 at 20:00
  • I don't think that this is the problem. Even when I reduce the dpi to 50 I get an image with 3x450 pixel, so the image should have enough pixel to hold my array. With array3 I should get a figure with 3x400 pixel or a multiple thereof!? Where are the additional 50 pixel (datapoints) coming from? – MarvinO_ Jan 10 '23 at 07:41
  • You are relying on `bbox_inches='tight'` to trim your figure to the correct size, and that is causing confusion. Figures are sized in inches, and by default 6.4 wide by 4.8 high. If you don't tailor your dpi or figure height to exactly match your image size, there will be interpolation in one direction or the other. Moreover, the image will not fill the whole 4.8 inches because there are margins. You are trimming those in the final output, but it means you have less than 4.8 inches. – Jody Klymak Jan 10 '23 at 18:41
  • This is essentially a duplicate of https://stackoverflow.com/questions/32889646/why-is-imshow-producing-images-with-more-pixels-than-i-have-put-in – Jody Klymak Jan 10 '23 at 18:41

0 Answers0