如何使用Matplotlib将多个矩形的重叠区域以不同颜色可视化
解决方案
你需要先安装几何计算库shapely用于计算矩形相交区域:
pip install shapely
完整实现代码
import matplotlib import matplotlib.pyplot as plt from shapely.geometry import Polygon from matplotlib.patches import Polygon as MplPolygon fig = plt.figure() ax = fig.add_subplot(111) # 定义原始矩形参数 (左下角x, 左下角y, 宽度, 高度, 填充颜色) rect_params = [ ((-675, -374), 744, 412, 'green'), ((-48, -454), 116, 491, 'blue'), ((-1009, -189), 1074, 225, 'yellow') ] shp_rects = [] for (x0, y0), w, h, color in rect_params: # 绘制原始矩形 rect = matplotlib.patches.Rectangle((x0, y0), w, h, color=color, alpha=0.6) ax.add_patch(rect) # 生成对应shapely几何对象用于后续交集计算 rect_pts = [(x0, y0), (x0+w, y0), (x0+w, y0+h), (x0, y0+h)] shp_rects.append(Polygon(rect_pts)) # 自定义相交区域样式,可按需修改 inter_style = { "two_rect": {"color": "red", "alpha": 0.9}, # 两个矩形相交区域样式 "three_rect": {"color": "purple", "alpha": 0.9} # 三个矩形相交区域样式 } # 计算并绘制所有两两相交的区域 for i in range(len(shp_rects)): for j in range(i+1, len(shp_rects)): inter_area = shp_rects[i].intersection(shp_rects[j]) if not inter_area.is_empty: inter_patch = MplPolygon(list(inter_area.exterior.coords), **inter_style["two_rect"]) ax.add_patch(inter_patch) # 计算并绘制三个矩形共同相交的区域 triple_inter_area = shp_rects[0].intersection(shp_rects[1]).intersection(shp_rects[2]) if not triple_inter_area.is_empty: triple_inter_patch = MplPolygon(list(triple_inter_area.exterior.coords), **inter_style["three_rect"]) ax.add_patch(triple_inter_patch) plt.xlim([-1100, 1100]) plt.ylim([-1100, 1100]) plt.show()
实现说明
- 所有相交区域的颜色、透明度、边框样式都可以根据需求自行调整
- 如果后续需要处理更多矩形,可以通过组合遍历的方式批量计算所有多矩形组合的相交区域,无需手动逐个定义
- 如果相交区域为离散的多块形状,只需额外判断
inter_area的类型为MultiPolygon后遍历inter_area.geoms逐个绘制即可
内容的提问来源于stack exchange,提问作者HB21
相关产品推荐
相关产品推荐

