Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
833 views
in Technique[技术] by (71.8m points)

python 3.x - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...