1

When saving in pdf format a figure displaying a picture (with matplotlib imshow), I noticed that the top and right line of pixels is only partially displayed. Moreover, this seems to be due to a scale issue, as when I plot say a square, there is an offset between the lines and the edges of the pixels that is dependent on the distance from lower left corner. I can see the effect with the following code:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches

rng = np.random.default_rng(seed=12345)
arr_img = rng.integers(50, size=(100, 100))

fig, ax = plt.subplots()
ax.axis("off")

im = ax.imshow(arr_img, interpolation="none", cmap="Greys")

verts = [(5.5, 5.5), (95.5, 5.5), (95.5, 95.5), (5.5, 95.5)]
poly = patches.Polygon(
    verts, facecolor="none", edgecolor="red", lw=0.1)
ax.add_patch(poly)

fig.savefig("./test.pdf")

It generates a picture on which you can see the edge pixels partially displayed (click on the picture to see it on a dark background, the lower and left edges appear clipped too but this is me clipping the corner of the image). The red square reveals the offset mentioned higher:

Lower left cornerUpper right corner

There is however no issue if the figure is saved as png, but the problem persists if I save the figure as svg.

What does cause this behavior and is there a way to circumvent this problem? I want to keep my figures in vector format.

johnc
  • 171
  • 4
  • Does this answer your question? [Pyplot imshow not showing square pixels when setting aspect ratio](https://stackoverflow.com/questions/54216002/pyplot-imshow-not-showing-square-pixels-when-setting-aspect-ratio) – Nelewout Mar 23 '22 at 15:17
  • @Nelewout No, the related question concerns the shape of the pixels in the bulk of the figure, the pixels of my figure are all square in the bulk. I think the problem is that the edge pixels are cropped for some reason. In any case the related question does not provide me with a way to fix my problem. – johnc Mar 23 '22 at 16:01
  • 1
    I cannot reproduce this problem. If zoomed in, border pixels within the displayed image might not be fully displayed in the current view. But panning reveals that all pixels are squares, including the [border pixels of the original image](https://imgur.com/n6HYIDC). matplotlib 3.5.1 and 3.3.4, Qt5Agg – Mr. T Mar 24 '22 at 08:15
  • @Mr.T I made my problem clearer I hope. The problem arises when saving the figure as a pdf or svg file. I indeed have no issue when the figure format is png. – johnc Mar 24 '22 at 13:14

0 Answers0