Reputation: 61
I am having this error when running a script. There is a way to correct it?
Thanks in advance
File "/usr/local/lib/python3.8/dist-packages/cartopy/mpl/geoaxes.py", line 718, in add_geometries
feature = cartopy.feature.ShapelyFeature(geoms, crs, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/cartopy/feature/__init__.py", line 221, in __init__
self._geoms = tuple(geometries)
TypeError: 'Polygon' object is not iterable
Here some python packages installed
Cartopy==0.18.0
Shapely==1.7.1
matplotlib==3.1.2
scipy==1.3.3
seaborn==0.9.0
def area(ax, iso, clr) :
shp = shpreader.natural_earth(resolution='10m',category='cultural',
name='admin_0_countries')
reader = shpreader.Reader(shp)
for n in reader.records() :
if n.attributes['ADM0_A3'] == iso:
ax.add_geometries(n.geometry, ccrs.PlateCarree(), facecolor=clr,
alpha = 1.00, linewidth =0.15, edgecolor = "black",
label=n.attributes['ADM0_A3'])
return ax
iso3 = ['CMR']
Upvotes: 2
Views: 1744
Reputation: 732
The method add_geometries
takes a collection of shapes as input. From the documentation:
add_geometries(geoms, crs, **kwargs)[source]
Add the given shapely geometries (in the given crs) to the axes. Parameters:
geoms
– A collection of shapely geometries.crs
– The cartopy CRS in which the provided geometries are defined.
When plotting a single country you need to provide an iterable (a list) with a single item (the country you want to plot) for it to work:
ax.add_geometries(
[n.geometry], ccrs.PlateCarree(), facecolor=clr,
alpha=1.00, linewidth=0.15, edgecolor="black",
label=n.attributes['ADM0_A3'])
Upvotes: 1
Reputation: 467
Instead of these lines:
if n.attributes['ADM0_A3'] == iso:
ax.add_geometries(n.geometry, ccrs.PlateCarree(), facecolor=clr, alpha = 1.00, linewidth =0.15, edgecolor = "black", label=n.attributes['ADM0_A3'])
Put these lines. Here we have added exception handling and then tried to convert 'Polygon' objects into 'MultiPolygon' objects that do not give error:
try:
ax.add_geometries(n.geometry, ccrs.PlateCarree(), facecolor=clr, alpha = 1.00, linewidth =0.15, edgecolor = "black", label=n.attributes['ADM0_A3'])
except Exception as e:
#print(e)
import shapely.wkt as wkt
from shapely.geometry import MultiPolygon
list_str_polygons = [str(n.geometry)]
c = MultiPolygon(map(wkt.loads, list_str_polygons))
ax.add_geometries(c, ccrs.PlateCarree(), facecolor=clr, alpha = 1.00, linewidth =0.15, edgecolor = "black", label=n.attributes['ADM0_A3'])
Upvotes: 2