在 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],#         [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,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')

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

,

在绘图之前,您必须仅选择 pointscitiesKingdom of Spain。相关代码如下:

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...