You can do this using the Axes
option set_rasterization_zorder
.
Anything with a zorder
less than what you set that to be will be saved as rasterized graphics, even when saving to a vector format like pdf
.
For example:
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(500,500)
# fig1 will save the contourf as a vector
fig1,ax1 = plt.subplots(1)
ax1.contourf(data)
fig1.savefig('vector.pdf')
# fig2 will save the contourf as a raster
fig2,ax2 = plt.subplots(1)
ax2.contourf(data,zorder=-20)
ax2.set_rasterization_zorder(-10)
fig2.savefig('raster.pdf')
# Show the difference in file size. "os.stat().st_size" gives the file size in bytes.
print os.stat('vector.pdf').st_size
# 15998481
print os.stat('raster.pdf').st_size
# 1186334
You can see this matplotlib example for more background info.
As pointed out by @tcaswell, to rasterise just one artist without having to affect its zorder
, you can use .set_rasterized
. However, this doesn't appear to be an option with contourf
, so you would need to loop over the PathCollections
created by contourf
and set_rasterized
on each of them. Something like this:
contours = ax.contourf(data)
for pathcoll in contours.collections:
pathcoll.set_rasterized(True)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…