2 years ago

#19437

test-img

Michael Dorner

Centeroids for countries in cartopy

I would like to use somehow meaningful centers for labels etc. Here is my code so far:

import cartopy.crs as ccrs
from cartopy.io import shapereader as shpreader
import matplotlib.pyplot as plt

geo_axes = plt.axes((2, 2, 2, 2), projection=ccrs.PlateCarree(central_longitude=0.0, globe=None))
geo_axes.set_global()

file = shpreader.natural_earth(resolution='10m', category='cultural', name='admin_0_countries')
all_countries = list(shpreader.Reader(file).records())

country_centroids = {country.attributes['SU_A3']: (country.geometry.centroid.y, country.geometry.centroid.x) for country in all_countries if country.attributes['SU_A3']}
for label in {'DEU', 'FRA', 'USA'}:
    geo_axes.plot(country_centroids[label][1], country_centroids[label][0], marker='x', color='red')

geo_axes.add_geometries([country.geometry for country in countries if country.attributes['SU_A3'] in {'DEU', 'FRA', 'USA'}], ccrs.PlateCarree(), facecolor='yellow', edgecolor='black', zorder=0)
geo_axes.add_geometries([country.geometry for country in countries if country.attributes['SU_A3'] not in {'DEU', 'FRA', 'USA'}], ccrs.PlateCarree(), facecolor='0.9', edgecolor='black', zorder=0)

enter image description here

For Germany, e.g., this is straight forward (no oversea regions, etc.) and it works. However, for USA, for example, it's already bad and, for example, for France it is very misleading (i.e. France's center is in Spain).

How can I fix that?

shapely

cartopy

centroid

0 Answers

Your Answer

Accepted video resources