简体   繁体   中英

GeoPandas Label Polygons

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!

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(text=x.NAME, xy=x.geometry.centroid.coords[0], ha='center'), axis=1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM