Matplotlib 地图和子图在每个数据点都有不同的文本

Matplotlib map and subplot with different text at each data point

我正在绘制一些数据,伦敦的气象站,并希望用气象站的名称标记每个数据点(绿色点),例如 Bow, Westminster。
该地图是从几何列的 Geopandas 数据框创建的。使用此 post: 我试图对文本进行注释,但出现以下错误:
TypeError: 'Point' object is not iterable

这是地图目前的样子:

这是代码:

f, ax = plt.subplots(1, figsize=(12, 12))
ax.set_title('Plot of London Grid for Learning weather stations with London boroughs and locations of Urban Mind datapoints', fontsize = 15)

boroughs.plot(alpha=1,edgecolor='w', facecolor='gray', linewidth=0.1, ax=ax)
london_umdata_geo.plot(ax=ax, marker="o",color="red",markersize=10.0,alpha=1.0, legend=True) #1,015 UM datapoints in London
stations_geo.plot(ax=ax, marker="X",color='green',markersize=20.0,alpha=1.0,legend=True)


n = stations_geo['Station Name'].tolist()
for i, txt in enumerate(n):
    ax.annotate(txt, xy = stations_geo.loc[i,'geometry'])

plt.show()

车站是绿色的点,其他数据点(不会标注)是红色的。

stations_geo 是一个 GeoPandas 数据框,它包含一个 geometry 列,使用 matplotlib 从中绘制点。

我正在为注释方法使用循环,据说循环遍历几何列中的点并将它们用作注释的坐标,但 matplotlib 似乎不喜欢 Point 对象(Shapely点)。然而,这些点首先被直接用于创建绿点,所以我不确定我哪里出错了。

感谢任何帮助,谢谢!

你自己已经找到问题了("matplotlib seems not to like the Point objects (which are Shapely points)")。

所以当你遇到这样的问题时,可以参考下面的文档。

  1. 查看 matplotlib documentation 关于您可以提供给 annotatexy 参数的内容。

    xy : iterable
    Length 2 sequence specifying the (x,y) point to annotate

  2. 看看你拥有的对象。如有疑问,请使用 print(type(stations_geo.loc[i,'geometry']))。它会显示类似 shapely.geometry.Point 的内容。看看the documentation of that object.

  3. 确定一种将一个转换为另一个的方法。在这种情况下,您会发现

    Coordinate values are accessed via coords, x, y, and z properties.

  4. 打印stations_geo.loc[i,'geometry'].coords,它将是(单个)元组的列表。 因此,为了将单个形状 Point 转换为 python 元组,您将使用其 .coords 属性并从该列表中获取第一个(也是唯一一个)元素。

    xy = stations_geo.loc[i,'geometry'].coords[0]