You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用matplotlib.patches实现带透明圆形孔的不透明白色背景?

实现白色背景带透明圆形孔洞的Matplotlib图像

要实现“白色纸张挖圆形孔洞”的效果,不能用普通的Circle叠加alpha的方式——因为Matplotlib的图层是从上到下绘制的,白色背景会覆盖圆形的透明效果。正确的做法是使用路径布尔运算创建“挖去圆形的矩形”,让圆形区域自然透出底层的透明,而矩形区域保持白色不透明。

完整实现代码

import matplotlib.pyplot as plt
from matplotlib.patches import PathPatch
from matplotlib.path import Path

# 初始化画布与坐标轴
fig, ax = plt.subplots(figsize=(4, 4))
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.axis('off')  # 隐藏冗余坐标轴

# 定义覆盖整个画布的矩形路径
rect_vertices = [
    (0, 0), (1, 0), (1, 1), (0, 1), (0, 0)
]
rect_path = Path(rect_vertices)

# 定义圆形路径,并平移缩放到画布中心(半径0.1)
circle_path = Path.unit_circle()
circle_transform = plt.matplotlib.transforms.Affine2D().scale(0.1).translate(0.5, 0.5)
circle_path = circle_path.transformed(circle_transform)

# 创建复合路径:矩形减去圆形(实现挖洞效果)
combined_path = Path.make_compound_path(rect_path, circle_path)
# 绘制复合路径,填充白色,无描边
path_patch = PathPatch(combined_path, facecolor='white', edgecolor='none')

ax.add_patch(path_patch)

# 保存图像,无需设置transparent=True
plt.savefig("circle_with_hole.pdf", dpi=300)
plt.show()

关键原理说明

  • Path.make_compound_path默认使用DIFFERENCE布尔运算:以第一个路径(矩形)为基础,减去第二个路径(圆形),最终得到的区域是“矩形区域减去圆形区域”。
  • 挖空的圆形区域不会被白色填充,因此保存为PDF/PNG时,该区域会呈现透明效果,而矩形区域保持不透明白色。
  • 无需设置plt.savefig(transparent=True),因为我们已经通过路径运算明确定义了白色区域的范围,背景透明仅存在于挖空的圆形部分。

内容的提问来源于stack exchange,提问作者Amos Egel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 15:29:58