I've got a contourf figure in matplotlib that is about 5 megs. Any suggestions on how to reduce the size?
Asked
Active
Viewed 1,626 times
3
-
The figure occupies 5 megabytes of resident memory? Or 5 megabytes when rasterized and written to a file? – Brian Cain Oct 21 '15 at 02:35
-
5 megs when written to disk in pdf format. – user2379888 Oct 21 '15 at 03:21
-
A PDF can be worst case for some datasets since it will typically preserve the vectors. Though my experience is usually with scatter plots. Try rasterizing to a PNG instead. If that works you can embed the PNG in a PDF in a separate step. – Brian Cain Oct 21 '15 at 03:22
-
Is there a way to rasterize the plot, but keep the axes labels and title as vector data? – user2379888 Oct 21 '15 at 03:34
-
Yes, apparently: http://stackoverflow.com/a/5638626/489590 – Brian Cain Oct 21 '15 at 03:36
-
1@BrianCain that works for some types of Axes object, but not `contourf`. See my answer for a way around this – tmdavison Oct 21 '15 at 10:13
1 Answers
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