使用matplotlib绘制多边形的并集

9

我正在尝试在matplotlib中绘制一些多边形的并集,并且希望设置一定的透明度。我的当前代码会在交叉处产生较暗的颜色。有没有办法使交叉处的颜色与其他地方相同?

import matplotlib.pyplot as plt

fig, axs = plt.subplots()
axs.fill([0, 0, 1, 1], [0, 1, 1, 0], alpha=.25, fc='r', ec='none')
axs.fill([0.5, 0.5, 1.5, 1.5], [0.5, 1.5, 1.5, 0.5], alpha=.25, fc='r', ec='none')

Generated plot


2
使用Shapely:如何合并多边形 - unutbu
1个回答

12

正如@unutbu和@Martin Valgur的评论所示,我认为shapely是最好的选择。这个问题可能与之前的一个问题有些冗余,但下面是一段干净的代码片段,应该可以满足您的需求。

策略是首先创建您各种形状(矩形)的并集,然后绘制该并集。这样,您就将不同的形状“平铺”成一个单一的形状,因此在重叠区域中没有alpha问题。

import shapely.geometry as sg
import shapely.ops as so
import matplotlib.pyplot as plt

#constructing the first rect as a polygon
r1 = sg.Polygon([(0,0),(0,1),(1,1),(1,0),(0,0)])

#a shortcut for constructing a rectangular polygon
r2 = sg.box(0.5,0.5,1.5,1.5)

#cascaded union can work on a list of shapes
new_shape = so.cascaded_union([r1,r2])

#exterior coordinates split into two arrays, xs and ys
# which is how matplotlib will need for plotting
xs, ys = new_shape.exterior.xy

#plot it
fig, axs = plt.subplots()
axs.fill(xs, ys, alpha=0.5, fc='r', ec='none')
plt.show() #if not interactive

绘制两个矩形的并集


请注意,现在建议在Shapely中使用so.unary_union而不是so.cascaded_union。当前文档链接:https://shapely.readthedocs.io/en/stable/manual.html#shapely.ops.cascaded_union - Eskapp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接