Search code examples
plotlypolygonplotly-python

Can Plotly for Python plot a polygon with one or multiple holes in it?


A simple example would be

shape_a = Point(0,0).buffer(10)
shape_b = Point(0,0).buffer(5)
shape_c = shape_a-shape_b

Ring Shape


Solution

  • Update: Well. fill='toself' also works, if the boundary coords of the holes are appended (separated by None) to the exterior coords in an opposite clock direction.

    I found a workaround myself, by using fill='tonext'. Prerequisite is you need to draw the interior boundary right before the exterior one. In the scenario of multiple holes, you will have to connect them first in one scatter object, via 'None' in the coords lists.

    shape_a = Point(0,0).buffer(10)
    shape_b = Point(0,0).buffer(2)
    shape_d = Point(5,0).buffer(1)
    
    shape_c = shape_a - shape_b
    shape_c = shape_c - shape_d
    
    fig = go.Figure(layout=go.Layout(width=640, height=640))
    x_a, y_a = shape_a.exterior.xy
    x_b, y_b = shape_b.exterior.xy
    x_d, y_d = shape_d.exterior.xy
    int_x = list(x_b) +  [None] + list(x_d)
    int_y = list(y_b) +  [None] + list(y_d)
    
    
    fig.add_trace(go.Scatter(x=list(int_x), y=list(int_y), fill='none', showlegend=False))
    fig.add_trace(go.Scatter(x=list(x_a), y=list(y_a), name='polygon_with_holes', fill='tonext'))