This question already has an answer here:
How to draw the union shape of rectangles in python

(1个答案)


5年前关闭。




我正在尝试在matplotlib中绘制具有一定水平的alpha的两个多边形的并集。我下面的当前代码在十字路口处具有较深的颜色。无论如何,要使交叉点与其他地方的颜色相同吗?
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')

python - 在matplotlib中绘制多边形的并集-LMLPHP

最佳答案

正如@unutbu和@Martin Valgur的评论所表明的那样,我认为要走的路很匀称。这个问题在早期版本中可能有点多余,但是这里有一个干净的代码段可以满足您的需求。

策略是首先创建各种形状(矩形)的并集,然后绘制并集。这样,您就可以将各种形状“展平”为单个形状,因此在重叠区域中不会出现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

python - 在matplotlib中绘制多边形的并集-LMLPHP

关于python - 在matplotlib中绘制多边形的并集,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34475431/

10-12 21:20