简体   繁体   中英

How to put a Geopandas plot on top of a matplotlib pyplot image?

At the moment, I have a plot of a certain geographic area that is coming from cartopy and I have a geometry object plotted from Geopandas, but no matter what I do I can't get them to combine into one plot. The axes are the same for both and I can actually get the axes of the geometry object onto the geographic area, but then my shape disappears.

Here is the relevant section of code:

from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
import cartopy.io.img_tiles as cimgt
import geopandas as gpd   
from matplotlib import pyplot as plt   
                
                
# Plotting the trade area graph
trade_geo_df = trade_area_response.json()['data']
trade_geo_df = gpd.GeoDataFrame(trade_geo_df)
trade_geo_df.loc[:, 'coordinates'] = trade_geo_df.coordinates.map(lambda x: x[0])
trade_geo_df['geometry'] = trade_geo_df.coordinates.apply(shapely.geometry.Polygon)
trade_geo_df['geometry'].plot()   
plt.plot(placer_lng, placer_lat, markersize=2, marker='o', color='red')  # Just a red dot

fig = plt.figure()
stamen_terrain = cimgt.Stamen('terrain-background')
        
# Limit the extent of the map to a small longitude/latitude range
ax = fig.add_subplot(1, 1, 1, projection=stamen_terrain.crs)
ax.set_extent([-89, -86, 41, 43], crs=ccrs.Geodetic())
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=2, color='gray', alpha=0.5, linestyle='--')
gl.ylabels_right = False
gl.xlabels_top = False
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
gl.xlabel_style = {'size': 10, 'color': 'gray'}
gl.ylabel_style = {'size': 10, 'color': 'gray'}
            
ax.add_image(stamen_terrain, 8)
            
ax.plot(placer_lng, placer_lat, markersize=2, marker='o', color='red', transform=ccrs.Geodetic())  # Just another red dot
plt.show()

For more information, the following is the trade_geo_df['geometry'] that is mentioned in the code block:

Out[4]: 
0    POLYGON ((-87.94035 41.93909, -87.93965 41.939...
1    POLYGON ((-87.88849 42.01734, -87.88676 42.016...
2    POLYGON ((-87.92825 42.02102, -87.92652 42.020...
3    POLYGON ((-87.86428 42.04548, -87.86255 42.045...
4    POLYGON ((-87.86947 42.05987, -87.86774 42.059...
5    POLYGON ((-87.87466 42.08422, -87.87293 42.084...
6    POLYGON ((-88.03025 42.10923, -88.02852 42.109...
7    POLYGON ((-88.01296 42.10972, -88.01123 42.109...
8    POLYGON ((-87.90750 42.12355, -87.90577 42.123...
9    POLYGON ((-88.01296 42.13131, -88.01123 42.130...
Name: geometry, dtype: geometry

And finally these are the two figures that come up. They have the same axes and I'm just trying to get them to line up on one figure (red dot is in the same location in both, but I know there's something I'm missing.

地理区域

我想要的贸易区

I've tried setting the axes for the geometry object to be the same as the geographic image, turning them into subplots of the same figure, switching the zorder and putting them in the same figure, etc. but nothing seems to work. I don't have much experience with plotting so any help would be appreciated.

I rearranged your lines of code to their proper places, added/corrected projection data where necessary. The unrelevant lines are commented out. Finally, here is the resulting code that you can try.

from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
import cartopy.io.img_tiles as cimgt
import geopandas as gpd   
from matplotlib import pyplot as plt  
import cartopy.crs as ccrs

stamen_terrain = cimgt.Stamen('terrain-background')
fig, ax = plt.subplots(figsize=(8,6), subplot_kw={'projection': stamen_terrain.crs})

ax.set_extent([-89, -86, 41, 43], crs=ccrs.PlateCarree())

# Plotting the trade area graph
#trade_geo_df = trade_area_response.json()['data']
#trade_geo_df = gpd.GeoDataFrame(trade_geo_df)
#trade_geo_df.loc[:, 'coordinates'] = trade_geo_df.coordinates.map(lambda x: x[0])
#trade_geo_df['geometry'] = trade_geo_df.coordinates.apply(shapely.geometry.Polygon)
#trade_geo_df['geometry'].plot(ax=ax)   
ax.plot(-87, 42, markersize=20, marker='o', color='red', transform=ccrs.PlateCarree(), zorder=100)  # Just a red dot

gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=2, color='gray', alpha=0.5, linestyle='--')
gl.ylabels_right = False
gl.xlabels_top = False
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
gl.xlabel_style = {'size': 10, 'color': 'gray'}
gl.ylabel_style = {'size': 10, 'color': 'gray'}

ax.add_image(stamen_terrain, 8)
#ax.plot(placer_lng, placer_lat, markersize=2, marker='o', color='red', transform=ccrs.Geodetic())  # Just another red dot
plt.show()

Output:-

红湖

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM