我试图在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')
答案 0 :(得分:8)
正如@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