在多边形区域之间填充

我想填充两个矩形之间的区域。有一种方法可以只使用fill_between或fill_betweenx中的一个吗?

通过组合下面的代码中所示的两个功能,我能够产生所需的结果。但是我不知道这是最好的方法。以下是唯一的小示范。有许多同心多边形,它们的中间区域我要用不同的颜色填充。

import matplotlib.pyplot as plt
x1 = [3,6,3,3]
y1 = [2,2,4,2]
x2 = [0,9,0]
y2 = [0,0]


plt.plot(x1,y1)
plt.plot(x2,y2)
plt.fill_betweenx(y1,x1,x2,color='blue')
plt.fill_between(x2,y1,y2,color='blue')

https://i.stack.imgur.com/h19uH.png

zdh064105 回答:在多边形区域之间填充

如果要处理与相交,并集或差异有关的几何对象,我将看看形状良好的模块Shapely - PyPI

在下面的示例中,您可以使用两个矩形

import matplotlib.pyplot as plt
from shapely.geometry import Polygon

x1 = [3,3,6,3]
y1 = [4,8,4,4]
x2 = [1,1,1]
y2 = [1,1]

fig,ax1 = plt.subplots(figsize=(6,4))

ax1.set_xlim(0,10)
ax1.set_ylim(0,10)

rectangle_1 = Polygon([*zip(x1,y1)])
rectangle_2 = Polygon([*zip(x2,y2)])

intersection = rectangle_1.intersection(rectangle_2)
union = rectangle_1.union(rectangle_2)
difference_1_2 = rectangle_1.difference(rectangle_2)
difference_2_1 = rectangle_2.difference(rectangle_1)

# ax1.plot(*rectangle_1.exterior.xy)
# ax1.plot(*rectangle_2.exterior.xy)
# ax1.plot(*intersection.exterior.xy)
# ax1.plot(*union.exterior.xy)
# ax1.plot(*difference_1_2.exterior.xy)
ax1.plot(*difference_2_1.exterior.xy)

plt.show()

在上面,我绘制了大矩形和小矩形的差异,这从大矩形中“切出”了小矩形的重叠部分。 取消注释绘图线会显示其他选项的结果。 enter image description here

,

如您所见,使用较大多边形与完全嵌入较大多边形中的一个较小多边形的差异会带来如何绘制此多边形对象的问题。正确地正确定义差异多边形,但仅绘制外部,这只会绘制较大的多边形。

我还没有找到使用matplotlib进行绘制的简单解决方案。我找到的解决方案来自此站点Painting punctured polygons with matplotlib。通过使用mpl path模块绘制外部的xy点和内部的xy点,它将Polygon对象转换为mpl pathpatch对象。 (例如,请参见Path Tutorial - Matplotlib中的路径工作原理)

'''
see: https://sgillies.net/2010/04/06/painting-punctured-polygons-with-matplotlib.html
'''
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch
from shapely.geometry import Polygon

def ring_coding(ob):
    # The codes will be all "LINETO" commands,except for "MOVETO"s at the
    # beginning of each subpath
    n = len(ob.coords)
    codes = np.ones(n,dtype=Path.code_type) * Path.LINETO
    codes[0] = Path.MOVETO
    return codes

def pathify(polygon):
    # Convert coordinates to path vertices. Objects produced by Shapely's
    # analytic methods have the proper coordinate order,no need to sort.
    vertices = np.concatenate(
        [np.asarray(polygon.exterior)]
        + [np.asarray(r) for r in polygon.interiors])
    codes = np.concatenate(
        [ring_coding(polygon.exterior)]
        + [ring_coding(r) for r in polygon.interiors])
    return Path(vertices,codes)

x1 = [3,3]
y1 = [2,2,2]
x2 = [0,9,0]
y2 = [0,0]

fig,4))

ax1.set_xlim(-1,10)
ax1.set_ylim(-1,y2)])

difference_2_1 = rectangle_2.difference(rectangle_1)
difference_2_1 = pathify(difference_2_1)
patch = PathPatch(difference_2_1,facecolor='blue',edgecolor='red')
ax1.add_patch(patch)

plt.show()

enter image description here

现在我简直不敢相信这是最简单的解决方案,所以如果有人有更好的方法,请告诉我!

本文链接:https://www.f2er.com/3120338.html

大家都在问