Home > Net >  Color Overlapping Polygons in Shapely Python
Color Overlapping Polygons in Shapely Python

Time:08-03

I am working with a set of overlapping circles in Shapely. I am trying to figure out how to color each circle fragment in my results list.

Here's my code:

import matplotlib.pyplot as plt
from shapely.geometry import Point, LineString, Polygon, MultiPoint, MultiPolygon
from shapely.ops import unary_union, polygonize


def plot_coords(coords):
    pts = list(coords)
    x, y = zip(*pts)
    plt.plot(x,y)


def plot_polys(polys):
    for poly in polys:
        plot_coords(poly.exterior.coords)
        plt.fill_between(*poly.exterior.xy, alpha=.5)


points = [Point(0, 0),
             Point(2,0),
             Point(1,2),
             Point(-1,2),
             Point(-2,0),
             Point(-1,-2),
             Point(1,-2)]

# buffer points to create circle polygons

circles = []
for point in points:
    circles.append(point.buffer(2.25))

# unary_union and polygonize to find overlaps

rings = [LineString(list(pol.exterior.coords)) for pol in circles]
union = unary_union(rings)
result = [geom for geom in polygonize(union)]

# plot resulting polygons

plot_polys(result)
plt.show()

Here's the plot:

enter image description here

In this example, 7 points buffered by 2.25 results in a total of 43 polygons due to all of the overlap. I want to choose the colors for each of the 43 segments. Results is a list object, so I am wondering if I can add a variable for color to each list item, or if I need to add the color in the plot_coords or plot_polys functions.

I have tried changing the "facecolor" and "linewidth" in the plt.fill_between line, from enter image description here

  • Related