3

I've got a contourf figure in matplotlib that is about 5 megs. Any suggestions on how to reduce the size?

user2379888
  • 1,145
  • 1
  • 10
  • 16

1 Answers1

2

The issue is that you have many elements of the contourf

For some types of Axes objects, you can set the rasterized option to True right when you call the plotting function. For example, with pcolormesh, you can use

plt.pcolormesh(some_array,rasterized=True)

However, for contourf this does not seem to work, but there is a way around it. You can set the zorder to some low number, then set the rasterization_zorder for the Axes to some number above that, and when you save the figure, it the QuadContourSet returned by contourf will be rasterized.

For example:

plt.contourf(some_array,zorder=-9)
plt.gca().set_rasterization_zorder(-1)

Below, I show some example file sizes after plotting a np.random.rand array of shape (500,500).

import matplotlib.pyplot as plt
import numpy as np

my_array = np.random.rand(500,500)

plt.contourf(my_array)
plt.savefig('contourf1.pdf')
plt.close()

plt.contourf(my_array,rasterized=True) # this won't work
plt.savefig('contourf2.pdf')
plt.close()

plt.contourf(my_array,zorder=-9)
plt.gca().set_rasterization_zorder(-1)
plt.savefig('contourf3.pdf')
plt.close()

Which gives the following three files:

$ ls -l contour?.pdf
-rw-r--r-- 1 tom 22804867 Oct 21 10:59 contourf1.pdf
-rw-r--r-- 1 tom 22808387 Oct 21 11:01 contourf2.pdf
-rw-r--r-- 1 tom   851117 Oct 21 11:03 contourf3.pdf

notice the much smaller file size for the third file.

tmdavison
  • 64,360
  • 12
  • 187
  • 165