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.

tiago
  • 22,602
  • 12
  • 72
  • 88
gertjan
  • 843
  • 1
  • 8
  • 16

1 Answers1

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

tiago
  • 22,602
  • 12
  • 72
  • 88
  • 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! – gertjan Dec 26 '12 at 10:03
  • 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`... – weronika Feb 28 '13 at 21:04
  • @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. – tiago Mar 01 '13 at 12:43
  • I looked into it some more - apparently there's a patch for the dpi issue and someone's working on getting it into matplotlib - https://github.com/matplotlib/matplotlib/pull/1185 – weronika Mar 06 '13 at 15:18
  • @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. – tiago Mar 07 '13 at 09:59