如何使用Matplotlib填充两个嵌套矩形之间的区域
你可以通过构造带孔的自定义路径实现需求,核心是利用Matplotlib路径的evenodd填充规则,先定义外框大矩形的顶点,再定义内部小矩形的顶点,二者组成的复合路径会自动挖空内部区域,完美支持透明度设置,不会影响底层其他绘图元素。
实现原理:evenodd填充规则会统计指定区域被路径边界穿过的次数,奇数次判定为填充区、偶数次判定为非填充区,因此大矩形和内部小矩形的路径组合后,二者重叠的内部区域会被自动挖空,完全不需要叠加白色矩形遮挡。
修改后的完整代码如下:
import matplotlib.pyplot as plt from matplotlib.patches import Rectangle from matplotlib.path import Path from matplotlib.patches import PathPatch def main(): # Box 1 外框大矩形 x1_1, y1_1 = 1.0, 2.0 x1_2, y1_2 = 8.0, 9.0 height1 = y1_2 - y1_1 width1 = x1_2 - x1_1 # Box 2 内部小矩形 x2_1, y2_1 = 3.0, 4.0 x2_2, y2_2 = 7.0, 6.0 height2 = y2_2 - y2_1 width2 = x2_2 - x2_1 # Plot fig, ax = plt.subplots(nrows=1, ncols=1) ax.plot() # 构造带孔的复合路径 verts = [ # 外框大矩形顶点(顺时针顺序) (x1_1, y1_1), (x1_2, y1_1), (x1_2, y1_2), (x1_1, y1_2), (x1_1, y1_1), # 内部小矩形顶点(逆时针顺序) (x2_1, y2_1), (x2_1, y2_2), (x2_2, y2_2), (x2_2, y2_1), (x2_1, y2_1), ] codes = [ Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY, Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY, ] path = Path(verts, codes) # 创建填充补丁,可自定义颜色、透明度 fill_patch = PathPatch(path, facecolor='blue', alpha=0.3, edgecolor='none') ax.add_patch(fill_patch) # 保留两个矩形的边框 rectangle1 = Rectangle(xy=(x1_1, y1_1), width=width1, height=height1, fill=False) rectangle2 = Rectangle(xy=(x2_1, y2_1), width=width2, height=height2, fill=False) ax.add_patch(rectangle1) ax.add_patch(rectangle2) # 可根据需求调整坐标轴范围 ax.set_xlim(0, 9) ax.set_ylim(1, 10) plt.tight_layout() plt.savefig("box.png") plt.close(fig) if __name__ == "__main__": main()
该方案实现的填充区域内部完全透明,填充区的透明度可通过alpha参数自由调整,不会和图中其他底层元素产生冲突。
内容的提问来源于stack exchange,提问作者Gilfoyle
相关产品推荐
相关产品推荐

