2016-08-11 85 views
6

給定可用的形狀文件here:我想在地圖上標記每個多邊形(縣)。 GeoPandas可能嗎?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() 

在此先感謝!

回答

11

c['geometry']是由shapely.geometry.polygon.Polygon對象組成的系列。可以通過檢查

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

Shapely docs驗證這有一種方法representative_point()

返回保證是 幾何對象內的便宜地計算點。

聽起來非常適合需要標註多邊形對象的情況!然後,您可以爲您的geopandasdataframe創建新列,'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') 

enter image description here

+0

@Fantastic!謝謝。 –

8

無需環路,這裏是你如何與應用註釋:

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

優雅而簡單。 –

+1

你犯了一個錯字:'xy = x.coords'? – dmvianna

+0

接受的答案適用於我,但不是這個。這個例子有兩列,分別是'name'和'geometry'。當應用循環播放它們時,根據打印的內容,它並不是真正逐行獲取數據,它更像是逐列。 – h4k1m