3

I need to plot a list of disconnected circles which I have created for other purposes in shapely.

I was trying to do exactly as the example in http://toblerity.org/shapely/manual.html#cascading-unions shows (see code) but that works only if the circles overlap and the overall thing is connected (which is not in my case). As you can see by replacing the line

polygons = [Point(i, 0).buffer(0.7) for i in range(5)]

with

polygons = [Point(i, 0).buffer(0.7) for i in (0,4)]

that breaks with and AssertionError for the thing not being a Polygon by descartes (or by matplotlib failing assert vertices.ndim == 2 if one comments out the descartes assertion as a test)

Looking at the docs for matplotlib.path.Path it seems possible to use MOVETO to achieve this goal, but shapely does not seem to support it. Is this correct? What workarounds do I have?

Davide
  • 17,098
  • 11
  • 52
  • 68
  • Can't you just plot all the circles one after another? – David Zwicker Dec 19 '14 at 22:47
  • @DavidZwicker That is what I am doing right now, but it's unsatisfactory because i) there are too many circles and ii) I don't care about each one, but I care about the covered area, so a plot like b) of the shapely example would be perfect – Davide Dec 20 '14 at 01:52

1 Answers1

5

The following code works:

from shapely.ops import cascaded_union
from shapely.geometry import Point
import random
from matplotlib.patches import Polygon
import pylab as pl
import numpy as np

circles = [Point(random.random(), random.random()).buffer(random.random() * 0.1) 
            for i in range(100)]

polygons = cascaded_union(circles)

fig, ax = pl.subplots(figsize=(8, 8))

for polygon in polygons:
    mpl_poly = Polygon(np.array(polygon.exterior), facecolor="g", lw=0, alpha=0.4)
    ax.add_patch(mpl_poly)

ax.relim()
ax.autoscale()

the output:

enter image description here

Davide
  • 17,098
  • 11
  • 52
  • 68
HYRY
  • 94,853
  • 25
  • 187
  • 187
  • Thanks for your answer. This gives some clues, and it works in your example but it's still obscure. In particular, if/when there are so many circles for the figure to become connected, the `for polygon in polygons:` fails with a `TypeError: 'Polygon' object is not iterable`. I guess I can check if polygons is iterable and use the PolygonPatch approach when it isn't, but that seems so ugly. – Davide Dec 22 '14 at 16:16