mrbump
mrbump

Reputation: 33

Matplotlib PDF output does not respect zorder when using imshow

I am plotting multiple images in matplotlib using imshow as well as some vector data between them using the zorder keyword.

Minimal example:

import numpy as np
import matplotlib.pyplot as plt

img = np.arange(100).reshape((10,10))
plt.imshow(img, extent = [0.25, 0.75, 0.25, 0.75], zorder = 10)
plt.imshow(img, extent = [0.1, 0.9, 0.1, 0.9], zorder = 1)
plt.plot([0, 1], [0, 1], color = 'black', zorder = 5)
plt.axis([0, 1, 0, 1])

plt.savefig('img.png')

When exporting to PNG, the output is as expected. However, when saving to PDF (or EPS, SVG, ...), the zorder is not respected (the line is plotted over both images). It seems the two images are combined into a single one when they are exported. Saving the images as vectors instead of rasters by using pcolormesh instead of imshow works, but the resulting PDFs are huge when plotting large images. Is there a way to make this work with imshow?

Upvotes: 3

Views: 1225

Answers (1)

Steve Barnes
Steve Barnes

Reputation: 28380

This sounds like you should raise a bug report here - I did find a similar issue here but your problem looks different enough to merit a separate ticket.

What you could do is split your diagonal line manually into two sections rather than relying on the z order to hide it for you. Something like:

plt.plot([0, 0.25], [0, 0.25], color = 'black', zorder = 5)
plt.plot([0.75, 1], [0.75, 1], color = 'black', zorder = 5)

Replacing your:

plt.plot([0, 1], [0, 1], color = 'black', zorder = 5)

Update:

Given that your real world plot is probably a lot more complex than a straight line you could possibly take your top layer, your plot and find a mask/boundary where the two intercept the remove, (automatically), the portions of your lines that need to be hidden.

The other option would be to produce all of your layers as separate images and then layer them up using PIL but since the PNG output works OK you would probably be better off outputting as PNG and then converting to PDF or embedding as PDF as a work around.

Upvotes: 1

Related Questions