根据 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_points
和 spain_cities
代替代码中的 points
和 cities
。
关于python - 在我的图中绘制 Cartopy 中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67848465/