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

标签 python matplotlib cartopy

根据 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 感谢您的帮助。

最佳答案

在绘图之前,您必须仅选择西类牙王国城市。相关代码如下:

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

关于python - 在我的图中绘制 Cartopy 中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67848465/

相关文章:

python - 在 python 脚本中嵌入图标

python - 在 seaborn kdeplot 中设置置信度

python - 将多边形框添加到cartopy python

python - Cartopy 的极坐标图轴标签

python - 如何在 PyQt4 中选择性地设置文本的前景色

python - 无法理解 __lt__ 方法

python - 如何最好地分发具有 _large_ 数据依赖性的 python 包

python - Matplotlib:未对齐的颜色条刻度线?

python - 如何在现有绘图上绘制 matplotlib 中的 (x,y) 值?

cartopy - 使用 cartopy 检查地理坐标点是陆地还是海洋?