9

I am trying to plot the union of a couple of polygons in matplotlib, with a certain level of alpha. My current code below has a darker color at the intersections. Would there be anyway to make the intersections the same color with other places?

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

Yuxiang Wang
  • 8,095
  • 13
  • 64
  • 95
  • 2
    Using shapely: [How to Merge Polygons](http://deparkes.co.uk/2015/02/28/how-to-merge-polygons-in-python/) – unutbu Dec 26 '15 at 22:48

1 Answers1

12

As @unutbu and @Martin Valgur's comments indicate, I think shapely is the way to go. This question may be somewhat redundant with an earlier one, but here is a clean code snippet that should do what you need.

The strategy is to first create the union of your various shapes (rectangles) and then plot the union. That way you have 'flattened' your various shapes into a single one, so you don't have the alpha problem in overlapping regions.

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

svohara
  • 2,159
  • 19
  • 17
  • Note that it is now recommended to use so.unary_union rather than so.cascaded_union in Shapely. Link to the current documentation:https://shapely.readthedocs.io/en/stable/manual.html#shapely.ops.cascaded_union – Eskapp Nov 12 '20 at 14:39