【问题标题】:Matplotlib map and subplot with different text at each data pointMatplotlib 地图和子图在每个数据点具有不同的文本
【发布时间】:2018-08-04 11:19:50
【问题描述】:

我正在绘制伦敦的一些数据、气象站,并希望用气象站的名称标记每个数据点(绿点),例如 Bow, Westminster。
该地图是从几何列中的 Geopandas 数据框创建的。使用这篇文章:https://stackoverflow.com/questions/14432557/matplotlib-scatter-plot-with-different-text-at-each-data-point 我尝试注释文本,但收到以下错误:
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 从该列中绘制点。

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

任何帮助表示赞赏,谢谢!

【问题讨论】:

  • 有没有机会可以重现 (minimal reproducible example)?
  • 您好,不太清楚如何向您发送站数据,这将使它如此...stations_geo 是一个包含 4 列的 GeoPandas 数据框:Station_Name、纬度 (float)、经度 (float) 和几何,这是 BNG 坐标中的一个 Shapely 点。例如STATION_NAME纬度经度几何0贝宁汉51.436 -0.009 POINT(538488.73396071 172657.9218037352)1贝尔蒙特51.346 -0.203 POINT(525250.3766155766 162301.1070065825)2弓51.528 -0.028 POINT(536892.6139878684 182852.743870542)3布伦特51.552 -0.231 POINT(522747.2053606602 185161.702351622)跨度>
  • 抱歉,我一直无法弄清楚如何在 StackOverflow 中很好地格式化数据。桌子似乎很难。您无需担心生成红点的数据 (london_umdata_geo),因为我不需要对这些数据进行注释。非常感谢所有帮助
  • 我想这个问题与实际的电台无关,所以它应该很容易在问题内的简短 sn-p 内重现。
  • @ImportanceOfBeingErnest,是的,请参见上文。希望这可以帮助。 BNG = British National Grid 而stations_geo 中的纬度、经度点在UTC 坐标中

标签: python matplotlib gis geopandas


【解决方案1】:

您自己已经发现了问题(“matplotlib 似乎不喜欢 Point 对象(它们是 Shapely 点)”)。

所以遇到这样的问题,你可以使用如下文档。

  1. 查看matplotlib documentation,了解您可以为annotatexy 参数提供什么。

    xy:可迭代
    长度为 2 的序列,指定要注释的 (x,y) 点

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

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

    通过coordsxyz 属性访问坐标值。

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

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

【讨论】:

  • 感谢@ImportanceOfBeingEarnest - 非常有用的解释
猜你喜欢
  • 2013-01-04
  • 2020-12-19
  • 2020-11-24
  • 2016-12-10
  • 2017-07-26
  • 2015-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多