Plotting Shapely Multipolygon using Matplotlib
Shapely Polygon
object has attribute exterior
. Shapely MultiPolygon
object has Polygon
object sequence. You should iterate over those polygons. You can do that using attribute geoms
of MultiPolygon
.
Use this way:
import shapely.geometry as sg
import shapely.ops as so
import matplotlib.pyplot as plt
r1 = sg.Polygon([(0,0),(0,1),(1,1),(1,0),(0,0)])
r2 = sg.box(0.5,0.5,1.5,1.5)
r3 = sg.box(4,4,5,5)
new_shape = so.cascaded_union([r1, r2, r3])
fig, axs = plt.subplots()
axs.set_aspect('equal', 'datalim')
for geom in new_shape.geoms:
xs, ys = geom.exterior.xy
axs.fill(xs, ys, alpha=0.5, fc='r', ec='none')
plt.show()
An alternative, shorter way of plotting using @Kadir Şahbaz's answer:
new_shape = so.cascaded_union([r1, r2, r3])
# Plot each polygon shape directly
for geom in new_shape.geoms:
plt.plot(*geom.exterior.xy)
# Set (current) axis to be equal before showing plot
plt.gca().axis("equal")
plt.show()
Look at Plot shapefile with islands with matplotlib for example.
As with polygons you can use matplotlib paths and patches and there is a Python module dedicated to plot polygons from shapefiles using these functions Descartes.
new_shape= so.unary_union([r1, r2, r3])
from descartes import PolygonPatch
import matplotlib.pyplot as plt
BLUE = '#6699cc'
GRAY = '#999999'
fig = plt.figure()
ax = fig.gca()
ax.add_patch(PolygonPatch(new_shape, fc=GRAY, ec=BLUE, alpha=0.5, zorder=2 ))
ax.axis('scaled')
plt.show()