矢量图形的光栅化#

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

可以为每个艺术家指定是否应使用光栅化。这有助于减少大型艺术家的文件大小,同时为其他艺术家(如轴和文本)保持矢量图形的优势。例如,复杂的pcolormesh或者 contourf可以通过光栅化变得更简单。设置光栅化仅影响矢量后端,例如 PDF、SVG 或 PS。

默认情况下禁用光栅化。有两种启用方式,也可以组合使用:

光栅化艺术家的存储大小和分辨率由其物理大小和dpi传递给的参数 值决定savefig

笔记

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

import numpy as np
import matplotlib.pyplot as plt

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, constrained_layout=True)

# 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")
m = 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
无光栅化、光栅化、无光栅化、光栅化 z$<-10$
The PostScript backend does not support transparency; partially transparent artists will be rendered opaque.

脚本总运行时间:(0分2.150秒)

由 Sphinx-Gallery 生成的画廊