Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib: mixed export to pdf and png

I create a figure with matplotlib figure, axes = plt.subplots(nrows=3, ncols=2), plot various stuff axes[0,0].pcolormesh(...) and then export the figure to PDF figure.savefig('figure.pdf') or to PNG figure.savefig('figure.png').

I have to use PNG, because the PDF-file would be huge, but this makes the figure labels and other texts blurry.

Is there a way to export the figure to PDF -- so that labels, etc. are vector graphics -- but with the plots being exported to PNG within the resulting PDF-file? In short: export to PDF, but plots within that PDF to PNG (for small file sizes).

like image 445
dimitsev Avatar asked Sep 06 '25 04:09

dimitsev


1 Answers

This is one of the huge advantages of Matplotlib over other libraries. If you do:

fig, ax = plt.subplots()
ax.pcolormesh(np.random.randn(500, 500), rasterized=True)
fig.savefig('Test.pdf', dpi=50)

The axes and labels will still be vectors, but the pcolormesh will be rasterized at 50 dpi. Of course for publication you should used a higher dpi, but it still is excellent for reducing large data sets. Note that you will also get aliasing artifacts if you downsample data, so use with caution.

PDF with embedded raster

like image 63
Jody Klymak Avatar answered Sep 07 '25 20:09

Jody Klymak