减小矢量化等高线图的大小

Løi*_*ten 1 python graphics plot matplotlib

我想将填充的等高线图包含在pdf文档中(例如TeX文档).目前我使用pyplot小号contourf,并保存到pdfpyplot小号savefig.与此相关的问题是,与高分辨率相比,图的尺寸变得相当大png.

减小尺寸的一种方法当然是减少图中的水平数量,但是太少的水平会产生较差的情节.我正在寻找一种简单的方法,例如将绘图的颜色保存为png,将轴,刻度等保存为矢量化.

tmd*_*son 7

您可以使用该Axes选项执行此操作set_rasterization_zorder.

任何zorder小于你设置的东西都将被保存为光栅化图形,即使保存为矢量格式也是如此pdf.

例如:

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
Run Code Online (Sandbox Code Playgroud)

您可以看到此matplotlib示例以获取更多背景信息.


正如@tcaswell指出的那样,只要一个艺术家光栅化而不必影响它zorder,你就可以使用.set_rasterized.然而,这并不似乎是一个选项contourf,所以你需要循环过PathCollections的创建contourfset_rasterized他们每个人.像这样的东西:

contours = ax.contourf(data)
for pathcoll in contours.collections:
    pathcoll.set_rasterized(True)
Run Code Online (Sandbox Code Playgroud)