【问题标题】:GeoPandas Label PolygonsGeoPandas 标签多边形
【发布时间】:2021-04-01 23:58:29
【问题描述】:

鉴于可用的形状文件here:我想在地图中标记每个多边形(县)。 GeoPandas 可以做到这一点吗?

import geopandas as gpd
import matplotlib.pyplot as plt
%matplotlib inline

shpfile=<Path to unzipped .shp file referenced and linked above>
c=gpd.read_file(shpfile)
c=c.loc[c['GEOID'].isin(['26161','26093','26049','26091','26075','26125','26163','26099','26115','26065'])]
c.plot()

提前致谢!

【问题讨论】:

    标签: python-3.x matplotlib geopandas


    【解决方案1】:

    c['geometry'] 是由shapely.geometry.polygon.Polygon 对象组成的系列。您可以通过检查来验证这一点

    In [23]: type(c.ix[23, 'geometry'])
    Out[23]: shapely.geometry.polygon.Polygon
    

    Shapely docs 有一个方法representative_point()

    返回一个保证在 几何对象。

    听起来非常适合需要标记多边形对象的情况!然后,您可以为您的 geopandas dataframe'coords' 创建一个新列,就像这样

    c['coords'] = c['geometry'].apply(lambda x: x.representative_point().coords[:])
    c['coords'] = [coords[0] for coords in c['coords']]
    

    现在您有一组与每个多边形对象(每个县)相关的坐标,您可以通过遍历数据框来注释您的绘图

    c.plot()
    for idx, row in c.iterrows():
        plt.annotate(s=row['NAME'], xy=row['coords'],
                     horizontalalignment='center')
    

    【讨论】:

    • @太棒了!谢谢。
    • 可以使用text,而不是annotate,当您想将数据与背景进行对比时,这很方便:ax.text(row.coords[0], row.coords[1], s=row[variable], horizontalalignment='center', bbox={'facecolor': 'white', 'alpha':0.8, 'pad': 2, 'edgecolor':'none'})
    【解决方案2】:

    无需循环,以下是您可以使用 apply 进行注释的方法:

    ax = df.plot()
    df.apply(lambda x: ax.annotate(text=x['NAME'], xy=x.geometry.centroid.coords[0], ha='center'), axis=1);
    

    【讨论】:

    • 优雅简约。
    • 你打错字了吗:xy=x.coords
    • 如果有人来到这里并拥有与@h4k1m 相同的标签 -> 您需要将 x.geometry.centroid.coords[0] 设置为 xy 才能使此解决方案起作用
    • 感谢@Maik R。我认为我的代码最初是您建议的。但过了一段时间,我不知何故认为geometry 是不必要的,并编辑了解决方案以使其更优雅。我显然把它弄坏了。谢谢指正。
    • 如果有人在x.name 产生索引号的问题中运行x['name']
    猜你喜欢
    • 2021-03-21
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    相关资源
    最近更新 更多