python - 如何使用 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()
解决方案
如果矩形不旋转,则可以通过左侧的最大值、右侧的最小值来计算交点(顶部和底部类似)。
对于更复杂的十字路口,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()
推荐阅读
- python - 获取忽略透明像素的表面的平均颜色
- flutter - 从另一个页面调用 JSON 结果
- swiftui - SwiftUI - 'windows' 在 iOS 15.0 中已弃用:使用 UIWindowScene.windows
- python - 在 Jupyter 中进行任何可视化时内核死机
- r - 有没有办法让有序列表项在 Rmarkdown ioslides 的增量模式下显示得更快?
- python - 基于另一个列表中的序列迭代和求和第二个列表的元素
- bash - 是否可以使用 bash 在文字字符串中填充变量
- flutter - Flutter 移动 ListView 项目对齐错误
- java - Spring security Userdetails 无法转换为我自己的用户实现
- google-sheets-formula - 谷歌表格公式条件