Home > Enterprise >  Matplotlib: mixed export to pdf and png
Matplotlib: mixed export to pdf and png

Time:10-13

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

CodePudding user response:

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

  • Related