矢量图栅格化 — Matplotlib 3.10.3 文档

2025-11-03 11:19:25

矢量图栅格化#

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

是否使用栅格化可以根据每个绘图元素单独指定。这有助于减小大型绘图元素的文件大小,同时保持矢量图对其他绘图元素(如坐标轴和文本)的优势。例如,通过栅格化可以大大简化复杂的pcolormesh或contourf。栅格化设置仅影响矢量后端,如 PDF、SVG 或 PS。

栅格化默认是禁用的。有两种方法可以启用它,这两种方法也可以结合使用

在单个绘图元素上设置set_rasterized,或在创建绘图元素时使用关键字参数rasterized。

设置Axes.set_rasterization_zorder以栅格化所有`zorder`小于给定值的绘图元素。

栅格化绘图元素的存储大小和分辨率由其物理尺寸以及传递给savefig的dpi参数值决定。

注意

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

The PostScript backend does not support transparency; partially transparent artists will be rendered opaque.

参考

本示例展示了以下函数、方法、类和模块的使用

matplotlib.artist.Artist.set_rasterized

matplotlib.axes.Axes.set_rasterization_zorder

matplotlib.axes.Axes.pcolormesh / matplotlib.pyplot.pcolormesh

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

下载 Jupyter notebook: rasterization_demo.ipynb

下载 Python 源代码: rasterization_demo.py

下载 压缩包: rasterization_demo.zip

由 Sphinx-Gallery 生成的画廊