Note
We are going to demonstrate polygon plotting in this example with the help of folium
[1]:
import geopandas as gpd import folium import matplotlib.pyplot as plt
We make use of nybb dataset
[2]:
path = gpd.datasets.get_path('nybb') df = gpd.read_file(path) df.head()
Plot from the original dataset
[3]:
df.plot(figsize=(6, 6)) plt.show()
One thing to notice is that the values of the geometry do not directly represent the values of latitude of longitude in geographic coordinate system
[4]:
print(df.crs)
epsg:2263
As folium(i.e. leaflet.js) by default takes input of values of latitude and longitude, we need to project the geometry first
[5]:
df = df.to_crs(epsg=4326) print(df.crs) df.head()
epsg:4326
[6]:
Initialize folium map object
[7]:
m = folium.Map(location=[40.70, -73.94], zoom_start=10, tiles='CartoDB positron') m
Overlay the boundaries of boroughs on map with borough name as popup
[8]:
for _, r in df.iterrows(): #without simplifying the representation of each borough, the map might not be displayed #sim_geo = gpd.GeoSeries(r['geometry']) sim_geo = gpd.GeoSeries(r['geometry']).simplify(tolerance=0.001) geo_j = sim_geo.to_json() geo_j = folium.GeoJson(data=geo_j, style_function=lambda x: {'fillColor': 'orange'}) folium.Popup(r['BoroName']).add_to(geo_j) geo_j.add_to(m) m
Add marker showing the area and length of each borough
[9]:
df['lat'] = df.centroid.y df['lon'] = df.centroid.x df.head()
<ipython-input-1-7cd59e1b644a>:1: UserWarning: Geometry is in a geographic CRS. Results from 'centroid' are likely incorrect. Use 'GeoSeries.to_crs()' to re-project geometries to a projected CRS before this operation. df['lat'] = df.centroid.y <ipython-input-1-7cd59e1b644a>:2: UserWarning: Geometry is in a geographic CRS. Results from 'centroid' are likely incorrect. Use 'GeoSeries.to_crs()' to re-project geometries to a projected CRS before this operation. df['lon'] = df.centroid.x
[10]:
for _, r in df.iterrows(): folium.Marker(location=[r['lat'], r['lon']], popup='length: {} <br> area: {}'.format(r['Shape_Leng'], r['Shape_Area'])).add_to(m) m
[ ]: