矢量图形的栅格化#

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

是否使用栅格化可以针对每个艺术家指定。这对于减少大型艺术家的文件大小非常有用,同时保持其他艺术家的矢量图形优势,例如轴和文本。例如,复杂的 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.

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

由 Sphinx-Gallery 生成的画廊