减小矢量化等高线图的大小 [英] Reducing size of vectorized contourplot
问题描述
我想在 pdf 文档(例如 TeX 文档)中包含一个填充的等高线图.目前我正在使用 pyplot
s contourf
,并使用 pyplot
s savefig
.这样做的问题是,与高分辨率 png
相比,图的大小变得相当大.
I would like to include a filled contour plot to a pdf document (for example a TeX document).
Currently I am using pyplot
s contourf
, and saving to pdf
with pyplot
s savefig
. The problem with this is that the size of the plots becomes rather big as compared to a high resolution png
.
缩小尺寸的一种方法当然是减少绘图中的级别数,但级别太少会导致绘图效果不佳.我正在寻找一种简单的方法,例如将绘图的颜色另存为 png,将轴、刻度等保存为矢量化.
One way to reduce the size is of course to reduce the number of levels in the plot, but too few levels gives a poor plot. I'm searching for a simple way to for example let the colors of the plot be saved as a png, with the axes, ticks etc. to be saved vectorized.
推荐答案
您可以使用 Axes
选项 set_rasterization_zorder
.
You can do this using the Axes
option set_rasterization_zorder
.
zorder
小于您设置的任何内容都将保存为光栅化图形,即使保存为像 pdf
这样的矢量格式.
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
.
例如:
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
您可以查看这个 matplotlib 示例了解更多背景信息.
You can see this matplotlib example for more background info.
正如@tcaswell 所指出的,要在不影响其 zorder
的情况下只对一位艺术家进行光栅化,您可以使用 .set_rasterized
.但是,这似乎不是 contourf
的选项,因此您需要遍历 contourf
和 创建的
在他们每个人上.像这样:PathCollections
>set_rasterized
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)
这篇关于减小矢量化等高线图的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!