GeoPandas Label Polygons

元气小坏坏 提交于 2019-11-30 05:11:50

c['geometry'] is a series comprised of shapely.geometry.polygon.Polygon objects. You can verify this by checking

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

From the Shapely docs there is a method representative_point() that

Returns a cheaply computed point that is guaranteed to be within the geometric object.

Sounds ideal for a situation in which you need to label the polygon objects! You can then create a new column for your geopandas dataframe, 'coords' like so

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

Now that you have a set of coordinates pertaining to each polygon object (each county), you can annotate your plot by iterating through your dataframe

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

no need to loop, here is how you can annotate with apply:

ax = df.plot()
df.apply(lambda x: ax.annotate(s=x.NAME, xy=x.geometry.centroid.coords[0], ha='center'),axis=1);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!