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:
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.