Files
geopandas/doc/source/gallery/polygon_plotting_with_folium.ipynb
T
Martin Fleischmann ed68a95033 DOC: debug readthedocs and nbsphinx (#1838)
* don't execute

* list examples

* try with executed notebooks

* build intro, add pygeos

* auto build

* build the same as currently

* remove kernel name

* add few more

* revert choro

* add rest

* remove kernelspec

* clear choropleths

* build choropleths, clear choro_legends

* clear introduction

* remove kernelspec

* clean meta

* execute choro_legends

* always execute + exceptions

* fix cartopy plot
2021-02-19 23:44:26 +00:00

4.2 KiB

An example of polygon plotting with folium

We are going to demonstrate polygon plotting in this example with the help of folium

In [ ]:
import geopandas as gpd
import folium
import matplotlib.pyplot as plt

We make use of nybb dataset

In [ ]:
path = gpd.datasets.get_path('nybb')
df = gpd.read_file(path)
df.head()

Plot from the original dataset

In [ ]:
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

In [ ]:
print(df.crs)

As folium(i.e. leaflet.js) by default takes input of values of latitude and longitude, we need to project the geometry first

In [ ]:
df = df.to_crs(epsg=4326)
print(df.crs)
df.head()
In [ ]:
df.plot(figsize=(6, 6))
plt.show()

Initialize folium map object

In [ ]:
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

In [ ]:
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

In [ ]:
df['lat'] = df.centroid.y
df['lon'] = df.centroid.x
df.head()
In [ ]:
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
In [ ]: