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.

Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389
ReutKeller
  • 2,139
  • 4
  • 30
  • 84
  • Does this answer from StackOverflow help? https://stackoverflow.com/a/19189664/9778755 – StefanBrand_EOX Jan 22 '21 at 11:35
  • @Stefan not really, I want to plot the geopandas just like here https://gis.stackexchange.com/questions/294072/how-can-i-superimpose-a-geopandas-dataframe-on-a-raster-plot – ReutKeller Jan 24 '21 at 08:46

1 Answers1

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.

Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389
ReutKeller
  • 2,139
  • 4
  • 30
  • 84