首页 > 解决方案 > 如何使用 Matplotlib 以不同颜色可视化 2 个或更多矩形的交集

问题描述

我有这个使用 Matlplotlib 生成彩色矩形的演示代码。经过几个小时到处搜索后,我仍然不明白如何以不同的颜色可视化 2 个或更多矩形之间的交集。非常感谢。

import matplotlib
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

rect1 = matplotlib.patches.Rectangle((-675, -374),
                                    744, 412,
                                    color ='green')

rect2 = matplotlib.patches.Rectangle((-48, -454),
                                    116, 491,
                                    color ='blue')

rect3 = matplotlib.patches.Rectangle((-1009, -189),
                                    1074, 225,
                                    color ='yellow')

ax.add_patch(rect1)
ax.add_patch(rect2)
ax.add_patch(rect3)

plt.xlim([-1100, 1100])
plt.ylim([-1100, 1100])

plt.show()

实际绘图图像

标签: pythonmatplotlib

解决方案


如果矩形不旋转,则可以通过左侧的最大值、右侧的最小值来计算交点(顶部和底部类似)。

对于更复杂的十字路口,Shapely是一种替代方案。

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

def intersect_rectangles(rect1_xywh, rect2_xywh):
    (x1, y1), w1, h1 = rect1_xywh
    (x2, y2), w2, h2 = rect2_xywh
    x = max(x1, x2)
    y = max(y1, y2)
    w = min(x1 + w1, x2 + w2) - x
    h = min(y1 + h1, y2 + h2) - y
    w = w if w > 0 else 0
    h = h if h > 0 else 0
    return ((x, y), w, h)

fig, ax = plt.subplots()

rect1_xywh = ((-675, -374), 744, 412)
rect2_xywh = ((-48, -454), 116, 491)
rect3_xywh = ((-1009, -189), 1074, 225)

rect1 = Rectangle(*rect1_xywh, color='green')
rect2 = Rectangle(*rect2_xywh, color='blue')
rect3 = Rectangle(*rect3_xywh, color='yellow')

ax.add_patch(rect1)
ax.add_patch(rect2)
ax.add_patch(rect3)

intersect12_xywh = intersect_rectangles(rect1_xywh, rect2_xywh)
intersect13_xywh = intersect_rectangles(rect1_xywh, rect3_xywh)
intersect23_xywh = intersect_rectangles(rect2_xywh, rect3_xywh)
intersect123_xywh = intersect_rectangles(intersect_rectangles(rect1_xywh, rect2_xywh), rect3_xywh)

intersect12 = Rectangle(*intersect12_xywh, color='turquoise')
intersect13 = Rectangle(*intersect13_xywh, color='orange')
intersect23 = Rectangle(*intersect23_xywh, color='purple')
intersect123 = Rectangle(*intersect123_xywh, color='crimson')

ax.add_patch(intersect12)
ax.add_patch(intersect13)
ax.add_patch(intersect23)
ax.add_patch(intersect123)

ax.relim()
ax.autoscale_view()
plt.show()

矩形的交点


推荐阅读