2

I have written a loop that suppose to open raster from file, display it as rgb and then plot on top of it GeoPandas plot. The problem is that the plots do not appear on to of the rasters inside the loop:


shapes = gpd.read_file(r'shape/shapes.shp')
shapes.dropna(subset=['geometry'],inplace=True)

...
#opening the files with the tif
files = glob.glob(str(folder_) + '/**/*.tiff', recursive=True)

for i in files:
    the_file=str(i)
    match=re.search(r'\d{4}-\d{2}-\d{2}',the_file)
    d=match.group(0)
    
    #open image
                    
    src = rasterio.open(i)
    print(src.crs)
    #create rgb visualization
    fig, ax = plt.subplots(figsize=(20,10))
    ax=show(src.read([4,3,2]),transform=src.transform,title=d,vmin=0,vmax=30000)
    shapes.plot(ax=ax,facecolor='none', edgecolor='red')#,color='red',legend=True)

the results:
enter image description here

no polygons on top of the image.

When I print outside the loop with ax.get_figure() it does plot the polygons:

enter image description here

but when I add it to the script I don't get the plots when I show the image:

    src = rasterio.open(i)
    print(src.crs)
    #create rgb visualization
    cmap = ListedColormap(['red'], name='allred')
    fig, ax = plt.subplots(figsize=(20,10))
    ax=show(src.read([4,3,2]),transform=src.transform,title=d,vmin=0,vmax=30000)
    shapes.plot(ax=ax,facecolor='none', edgecolor='red')#,color='red',legend=True)
    ax.get_figure()

(result: same image with no polygons).

Why doesn't it show the polygons inside the loop? How can I solve it?

My end goal is to display the plots on top of the image inside my loop.

2
2

In the end what helped was to change the order and add plt.show():

fig, ax = plt.subplots(figsize=(15, 15))
    rasterio.plot.show(src.read([4,3,2]),transform=src.transform,title=d,vmin=0,vmax=30000, ax=ax)
    shapes.plot(ax=ax, facecolor='none', edgecolor='red')
    plt.show()

based on this answer.

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.