注意
跳到結尾以下載完整的範例程式碼。
向量圖形的點陣化#
點陣化將向量圖形轉換為點陣圖像(像素)。它可以加速渲染並為大型資料集產生較小的檔案,但代價是固定解析度。
是否應使用點陣化可以針對每個藝術家指定。這對於縮減大型藝術家的檔案大小,同時維持其他藝術家(例如軸和文字)的向量圖形優點很有用。例如,可以通過點陣化使複雜的 pcolormesh
或 contourf
明顯簡化。設定點陣化只會影響向量後端,例如 PDF、SVG 或 PS。
點陣化預設為停用。有兩種方法可以啟用它,也可以組合使用
在個別藝術家上設定
set_rasterized
,或在建立藝術家時使用關鍵字引數 rasterized。設定
Axes.set_rasterization_zorder
以點陣化所有 z 順序小於指定值的藝術家。
點陣化藝術家的儲存大小和解析度由其物理大小以及傳遞給 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.
參考文獻
此範例中顯示了以下函式、方法、類別和模組的使用
腳本的總執行時間:(0 分鐘 3.207 秒)