Reputation: 281
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:
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 this tutorial, but it isn't working right, so I'm unsure where the instructions for color are actually coming from.
Any help would be greatly appreciated!
Upvotes: 1
Views: 852
Reputation: 1345
I don't know if this is what you tried to do, but here I assign one color to every Polygon
import matplotlib.pyplot as plt
from shapely.geometry import Point, LineString
from shapely.ops import unary_union, polygonize
from matplotlib.pyplot import cm
import numpy as np
def plot_coords(coords, color):
pts = list(coords)
x, y = zip(*pts)
print(color)
plt.plot(x,y, color=color)
plt.fill_between(x, y, facecolor=color)
def plot_polys(polys, colors):
for poly, color in zip(polys, colors):
plot_coords(poly.exterior.coords, color)
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
colors = cm.rainbow(np.linspace(0, 1, len(result)))
plot_polys(result, colors)
plt.show()
Upvotes: 1