Skip to main content
 首页 » 编程设计

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

2025年05月04日17Leo_wl

我想在 pdf 文档(例如 TeX 文档)中包含一个填充轮廓图。 目前我正在使用 pyplotcontourf ,并使用 pyplots savefig 保存到 pdf .这样做的问题是,与高分辨率 png 相比,绘图的大小变得相当大。

减小尺寸的一种方法当然是减少情节中的层次数量,但是层次太少会导致情节不佳。我正在寻找一种简单的方法,例如将绘图的颜色保存为 png,并将轴、刻度等保存为矢量化。

请您参考如下方法:

您可以使用 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 

可以看到this matplotlib example了解更多背景信息。


正如@tcaswell 所指出的,要在不影响其zorder 的情况下只对一位艺术家进行栅格化,您可以使用.set_rasterized。但是,这似乎不是 contourf 的选项,因此您需要遍历由 contourf 和 创建的 PathCollections >set_rasterized 在他们每个人身上。像这样:

contours = ax.contourf(data) 
for pathcoll in contours.collections: 
    pathcoll.set_rasterized(True)