在我的图中绘制 Cartopy 中的文本

Plotting text in Cartopy just inside my figure

根据 Natural Earth 数据,我正在尝试绘制西班牙的一些大城市并用它们的名字标记它们。如果我只绘制点,使用 ax.scatter,我会正确地得到我的数字,没有点在它之外。但是当用同样的方法ax.text时,我得到了图片之外的世界所有城市的名称...

代码在这里:

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

# Downloaded from https://gadm.org/download_country_v3.html. Those are the borders
fname = 'C:/Users/lordf/Downloads/gadm36_ESP_shp/gadm36_ESP_2.shp'
adm1_shapes = list(shpreader.Reader(fname).geometries())

cname = shpreader.natural_earth(resolution='10m', category='cultural', name='populated_places')
reader = shpreader.Reader(cname) #data of cities

plt.figure(figsize=(10,10))

ax = plt.axes(projection=ccrs.PlateCarree())
ax.set_extent([-10, 1, 35, 45], ccrs.PlateCarree())
plt.title('Spain')
ax.coastlines(resolution='10m')

ax.add_geometries(adm1_shapes, ccrs.PlateCarree(),
                  edgecolor='black', facecolor='gray', alpha=0.5) #borders

points = list(reader.geometries())
cities = list(reader.records())

ax.scatter([point.x for point in points],
           [point.y for point in points],
           transform=ccrs.PlateCarree(),
           s=[10*np.exp(1/(city.attributes['SCALERANK']+1)) for city in cities], c='r')
          #trying to match the size of the point to the population

#This gives me error, dont know why:
# ax.text([point.x for point in points], [point.y for point in points], 
#         [city.attributes['NAME'] for city in cities], 
#         transform=ccrs.PlateCarree())

#This is what plots the text outside the figure:
for i in range(len(points)):
    ax.text(points[i].x, points[i].y, cities[i].attributes['NAME'], transform=ccrs.PlateCarree())

ax.set_extent([-10, 1, 35, 45], ccrs.PlateCarree())

plt.show()

This is part of the image output 感谢您的帮助。

首先,您可以创建一个数据框,其中包含城市名称、纬度和经度等信息。然后你可以这样做:

# add cities
for i in range(UK_cities.shape[0]):
    ax.text(UK_cities['lon'][i],UK_cities['lat'][i],UK_cities['City_name'][i],fontsize=15,weight='bold')

这里我只是复制了我用于绘制英国城市的代码。

在绘图之前,您必须 select 只有 pointsKingdom of Spaincities。这是相关代码:

spain_points = []
spain_cities = []
for city,xy in zip(cities, points):
    if city.attributes["SOV0NAME"]=="Kingdom of Spain":
        print(city.attributes["NAME"], xy)
        spain_points.append(xy)
        spain_cities.append(city)
        pass
    pass

然后用 spain_pointsspain_cities 代替代码中的 pointscities