GeoPandas examples¶
In the following examples we use the nybb dataset.
GeoPandas-Plot¶
Import
[1]:
import geopandas as gpd
from geodatasets import get_path
Read data
[2]:
nybb = get_path("nybb")
[3]:
df = gpd.read_file(nybb)
Display the first lines
[4]:
df.head()
[4]:
BoroCode | BoroName | Shape_Leng | Shape_Area | geometry | |
---|---|---|---|---|---|
0 | 5 | Staten Island | 330470.010332 | 1.623820e+09 | MULTIPOLYGON (((970217.022 145643.332, 970227.... |
1 | 4 | Queens | 896344.047763 | 3.045213e+09 | MULTIPOLYGON (((1029606.077 156073.814, 102957... |
2 | 3 | Brooklyn | 741080.523166 | 1.937479e+09 | MULTIPOLYGON (((1021176.479 151374.797, 102100... |
3 | 1 | Manhattan | 359299.096471 | 6.364715e+08 | MULTIPOLYGON (((981219.056 188655.316, 980940.... |
4 | 2 | Bronx | 464392.991824 | 1.186925e+09 | MULTIPOLYGON (((1012821.806 229228.265, 101278... |
Plotting
[5]:
ax = df.plot(figsize=(10, 10), alpha=0.5, edgecolor="k")

figsize
specifies the size of the plot, alpha
the transparency and edgecolor
the edge colour.
Plotting in Folium¶
Folium, or more precisely the leaflet.js uses the values for latitude and longitude by default. We therefore have to convert our values first:
Determine coordinates
To be able to use the data with EPSG codes, GeoPandas offers geopandas.GeoDataFrame.crs (spatial reference system).
[6]:
print(df.crs)
EPSG:2263
[7]:
df = df.to_crs(epsg=4326)
print(df.crs)
df.head()
EPSG:4326
[7]:
BoroCode | BoroName | Shape_Leng | Shape_Area | geometry | |
---|---|---|---|---|---|
0 | 5 | Staten Island | 330470.010332 | 1.623820e+09 | MULTIPOLYGON (((-74.05051 40.56642, -74.05047 ... |
1 | 4 | Queens | 896344.047763 | 3.045213e+09 | MULTIPOLYGON (((-73.83668 40.59495, -73.83678 ... |
2 | 3 | Brooklyn | 741080.523166 | 1.937479e+09 | MULTIPOLYGON (((-73.86706 40.58209, -73.86769 ... |
3 | 1 | Manhattan | 359299.096471 | 6.364715e+08 | MULTIPOLYGON (((-74.01093 40.68449, -74.01193 ... |
4 | 2 | Bronx | 464392.991824 | 1.186925e+09 | MULTIPOLYGON (((-73.89681 40.79581, -73.89694 ... |
[8]:
import folium
[9]:
m = folium.Map(
location=[40.70, -73.94], zoom_start=10, tiles="CartoDB positron"
)
for _, r in df.iterrows():
# without simplifying the representation of each borough, the map might not be displayed
sim_geo = gpd.GeoSeries(r["geometry"]).simplify(tolerance=0.001)
geo_j = sim_geo.to_json()
geo_j = folium.GeoJson(
data=geo_j,
)
folium.Popup(r["BoroName"]).add_to(geo_j)
geo_j.add_to(m)
m
[9]:
Make this Notebook Trusted to load map: File -> Trust Notebook