【问题标题】:Reducing size of vectorized contourplot减小矢量化等高线图的大小
【发布时间】:2016-09-03 18:53:14
【问题描述】:

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

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

【问题讨论】:

  • 我们能看到一个典型的情节吗?你玩过 nchunk 参数吗?
  • @tom 给出的例子给出了一个典型的情节。我没有使用 nchunck 参数,但出于我的目的,选择的答案就足够了。最佳

标签: python matplotlib plot graphics


【解决方案1】:

您可以使用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 的选项,因此您需要在每个contourfset_rasterized 上循环创建PathCollections。像这样的:

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

【讨论】:

  • 很好的答案,谢谢:D。对于那些想知道的人:zorder 较低的艺术家首先被绘制,低于set_rasterization_zorder 中给出的值的艺术家将被栅格化。
  • 您还可以在艺术家上使用set_rasterized 将其栅格化,而与 zorder 无关。
  • @tcaswell:是的,但并非所有艺术家都有这个选项。 contourf 返回一个matplotlib.contour.QuadContourSet 实例,它没有set_rasterized 选项。您可以遍历它在 ax.collections 中创建的 PathCollections 并在每个上面使用 set_rasterized,但我发现使用 set_rasterization_zorder 往往是一个更简单的选择
  • 啊,这就是 QuadContourSet 是一个表现不佳的容器。
猜你喜欢
  • 2019-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-05
  • 2020-01-07
  • 1970-01-01
  • 2023-03-13
相关资源
最近更新 更多