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

标签 python matplotlib plot shapely

<分区>

我试图在 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')

Generated plot

最佳答案

正如@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

Plotting union of two rectangles

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

相关文章:

plot - Gnuplot : how to make a gif by plotting one block of data after the other in the same file . 数据?

r - ChordDiagram 切断长标签

python - 如何使用 lxml 迭代 xml 数据以删除下一个重复元素

Python/代码学院 : Class average calculation

plot - gnuplot:跳过丢失的列

python - 执行plt.show()后Python没有响应

Python - 使用等高线图绘制两个 3D 图形

python - 如何使用Scrapy编码

python - 在同一测试中重用 pytest fixture

python - 图例中的错误栏- Pandas 栏图