1

I have 2D raster and I'm interested in plotting on top of it polygon. When I print the geometry and its' type I get this:

#this is inside a loop that takes each time one row which is one polygon
    for geom,ids in zip(tmp[col_geometry],tmp[col_plots]):
        print('geometry:{},type:{}'.format(geom,type(geom)))
....


geometry:POLYGON ((-53.770698 -12.17007, -53.770694 -12.17005, -53.770695 -12.17006, -53.770698 -12.17007)),type:<class 'shapely.geometry.polygon.Polygon'>

However, when I tried to plot this polygon on top of rasterio ,I received error:

            img=rasterio.open(tiff)
            fig, ax = plt.subplots(figsize=(12, 8))
            rasterio.plot.show(img,transform=img.transform,ax=ax,cmap='Spectral')
#plot all the polygons I have from the geopandas shapefile:
            tmp.plot(ax=ax, facecolor='none', edgecolor='red')
#plot the specific one polygon that was selected in this iteration:
            geom.plot(ax=ax, facecolor='none', edgecolor='green')
            plt.show()

the error:

AttributeError: 'Polygon' object has no attribute 'plot'

How can I plot this geometry on top of the raster (that has already the geopandas dataframe plot on it) ?

1

Using your existing Shapely Polygon geometry "geometry:POLYGON ((-53.770698 -12.17007, -53.770694 -12.17005, -53.770695 -12.17006, -53.770698 -12.17007)),type:<class 'shapely.geometry.polygon.Polygon'>" you can use the following:

Replace your below line:

geom.plot(ax=ax, facecolor='none', edgecolor='green')

With this one:

xs, ys = geom.exterior.xy
ax.fill(xs, ys, alpha=0.5, fc='r', ec='none')
0

I found a way to "bypass" this issue , by converting the polygon into geoseries,and then plot it. However, if there is any smarter ways I would love to learn.

 g = GeoSeries([geom])
...
 g.plot(ax=ax, facecolor='none', edgecolor='cyan',linewidth=3)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.