GeoPandas Label Polygons

僤鯓⒐⒋嵵緔 提交于 2019-11-28 21:19:03

问题


Given the shape file available here: I'd like to label each polygon (county) in the map. Is this possible with 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()

Thanks in advance!


回答1:


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')




回答2:


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);


来源:https://stackoverflow.com/questions/38899190/geopandas-label-polygons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!