矢量图形的栅格化#

光栅化将矢量图形转换为光栅图像(像素)。它可以加快渲染速度并为大数据集生成更小的文件,但代价是固定的分辨率。

是否使用光栅化可以在每个艺术家上指定。这对于减少大型艺术家的文件大小非常有用,同时保持其他艺术家如Axes和文本的矢量图形的优势。例如,复杂的 pcolormeshcontourf 可以通过光栅化显著简化。设置光栅化仅影响PDF、SVG或PS等矢量后端。

默认情况下,光栅化是禁用的。有两种方法可以启用它,也可以结合使用:

栅格化艺术家的存储大小和分辨率由其物理尺寸和传递给 savefigdpi 参数决定。

备注

HTML 文档中展示的这个示例的图像不是矢量图形。因此,它无法展示光栅化效果。请在本地运行此示例并检查生成的图形文件。

import matplotlib.pyplot as plt
import numpy as np

d = np.arange(100).reshape(10, 10)  # the values to be color-mapped
x, y = np.meshgrid(np.arange(11), np.arange(11))

theta = 0.25*np.pi
xx = x*np.cos(theta) - y*np.sin(theta)  # rotate x by -theta
yy = x*np.sin(theta) + y*np.cos(theta)  # rotate y by -theta

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, layout="constrained")

# pcolormesh without rasterization
ax1.set_aspect(1)
ax1.pcolormesh(xx, yy, d)
ax1.set_title("No Rasterization")

# pcolormesh with rasterization; enabled by keyword argument
ax2.set_aspect(1)
ax2.set_title("Rasterization")
ax2.pcolormesh(xx, yy, d, rasterized=True)

# pcolormesh with an overlaid text without rasterization
ax3.set_aspect(1)
ax3.pcolormesh(xx, yy, d)
ax3.text(0.5, 0.5, "Text", alpha=0.2,
         va="center", ha="center", size=50, transform=ax3.transAxes)
ax3.set_title("No Rasterization")

# pcolormesh with an overlaid text without rasterization; enabled by zorder.
# Setting the rasterization zorder threshold to 0 and a negative zorder on the
# pcolormesh rasterizes it. All artists have a non-negative zorder by default,
# so they (e.g. the text here) are not affected.
ax4.set_aspect(1)
m = ax4.pcolormesh(xx, yy, d, zorder=-10)
ax4.text(0.5, 0.5, "Text", alpha=0.2,
         va="center", ha="center", size=50, transform=ax4.transAxes)
ax4.set_rasterization_zorder(0)
ax4.set_title("Rasterization z$<-10$")

# Save files in pdf and eps format
plt.savefig("test_rasterization.pdf", dpi=150)
plt.savefig("test_rasterization.eps", dpi=150)

if not plt.rcParams["text.usetex"]:
    plt.savefig("test_rasterization.svg", dpi=150)
    # svg backend currently ignores the dpi
No Rasterization, Rasterization, No Rasterization, Rasterization z$<-10$
The PostScript backend does not support transparency; partially transparent artists will be rendered opaque.

由 Sphinx-Gallery 生成的画廊