I am trying to plot several polygons as overlays on an existing map with cartopy. However, I receive the following error AttributeError: 'GeoSeries' object has no attribute '_geom'
.
import cartopy.crs as ccrs
from cartopy.feature import ShapelyFeature
from matplotlib import pyplot as plt
import geopandas as gpd
ax = plt.axes(projection=ccrs.Mollweide())
ax.stock_img()
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
africa = world[(world['continent'] == 'Africa')]
shape_feature = ShapelyFeature([africa.geometry], ccrs.PlateCarree(), facecolor="lime", edgecolor='black', lw=1)
ax.add_feature(shape_feature)
plt.show()
The geodataframe africa
you have just created has a method .plot()
. So that you can plot it with an option ax=ax
that instructs the renderer to use the axis you created to plot on it.
import cartopy.crs as ccrs
from cartopy.feature import ShapelyFeature
from matplotlib import pyplot as plt
import geopandas as gpd
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
africa = world[(world['continent'] == 'Africa')]
proj = ccrs.PlateCarree()
ax = plt.axes(projection=proj)
africa.plot(ax=ax)
# Bad code
#shape_feature = ShapelyFeature([africa.geometry], ccrs.PlateCarree(), facecolor="lime", edgecolor='black', lw=1)
#ax.add_feature(shape_feature)
plt.show()
Answer to the updated question
The new version of the code:-
import cartopy
import cartopy.crs as ccrs
from cartopy.feature import ShapelyFeature
from matplotlib import pyplot as plt
import geopandas as gpd
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
africa = world[(world['continent'] == 'Africa')]
latlon_proj = ccrs.PlateCarree()
axis_proj = ccrs.Mollweide()
ax = plt.axes(projection=axis_proj)
ax.stock_img()
for ea in africa['geometry']:
feat = cartopy.feature.ShapelyFeature([ea], latlon_proj, facecolor="lime", edgecolor='black', lw=0.2)
ax.add_feature(feat)
#ax.add_feature(cartopy.feature.COASTLINE)
plt.show()
The output plot: