rasterizing matplotlib axis contents (but not frame, labels)
Asked Answered
B

1

13

For an article I am generating plots of deformed finite element meshes, which I visualize using matplotlib's polycollection. The images are saved as pdf.

Problems arise for high density meshes, for which the naive approach results in files that are too large and rendering too intensive to be practical.

For these meshes it really makes no sense to plot each element as a polygon; it could easily be rasterized, as is done when saving the image as jpg or png. However, for print I would like to hold on to a sharp frame, labels, and annotations.

Does anyone know if it is possible to achieve this kind of hybrid rasterization in matplotlib?

I can think of solutions involving imshow, and bypassing polycollection, but I would much prefer to use matplotlib's built-in components.

Thanks for your advice.

Biparty answered 25/12, 2012 at 17:43 Comment(0)
P
17

Just pass the rasterized=True keyword to your collection constructor. Example:

col = collections.PolyCollection(<arguments>, rasterized=True)

This allows a selective rasterization of that element only (e.g., if you did a normal plot on top of it, it would be vectorized by default). Most commands like plot or imshow can also take the rasterized keyword. If one wants to rasterize the whole figure (including labels and annotations), this would do it:

fig = plt.figure()
a = fig.add_subplot(1,1,1, rasterized=True)

(But this is not what you want, as stated in the question.)

Pretentious answered 26/12, 2012 at 4:6 Comment(5)
Wow, that simple. I worry about my googling skills now. But thank you so much for this answer, this is exactly what I was hoping for!Biparty
This is great! Any idea how to control the dpi of the rasterization, though? It seems to ignore the dpi I pass to figure and savefig...Wotan
@weronika, if the dpi in figure or savefig doesn't work, then I don't really know how to change it. collections seems to use the artist allow_rasterization decorator, but from a quick glance a the code I couldn't see how to set a dpi.Pretentious
I looked into it some more - apparently there's a patch for the dpi issue and someone's working on getting it into matplotlib - github.com/matplotlib/matplotlib/pull/1185Wotan
@weronika, interesting. From that discussion (which applies to the svg backend) it seems like the pdf backend already supports this. But doesn't seem like it in my version.Pretentious

© 2022 - 2024 — McMap. All rights reserved.