from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import geopandas as gpd
import altair as alt
pd.options.display.max_columns = 999
plt.rcParams['figure.figsize'] = (10,6)
Nov 3, 2021
Three parts:
import osmnx as ox
Haven't we already done this?
We've used hvplot, holoviews, datashader, etc. to create interactive map-based visualizations
Pros
Cons
OSMnx leverages Folium under the hood to make interactive graphs of street networks!
Key function: ox.plot_graph_folium
will make an interactive map of the graph object
Load the street network around City Hall
G = ox.graph_from_address('City Hall, Philadelphia, USA',
dist=1500,
network_type='drive')
# plot the street network with folium
graph_map = ox.plot_graph_folium(G,
popup_attribute='name',
edge_width=2)
ox.plot_graph_folium?
And now save the map object and load it into the Jupyter notebook
from IPython.display import IFrame # loads HTML files
filepath = 'graph.html'
graph_map.save(filepath)
IFrame(filepath, width=600, height=500)
Folium map objects are supposed to render automatically in the Jupyter notebook, so if you output a Folium map from a notebook cell, it will render.
However, there a lot of times when the map won't show up properly, especially if the map has a large amount of data. Saving the file locally and loading it to the notebook via an IFrame will always work.
type(graph_map)
graph_map
Let's calculate the shortest route between the Art Museum and the Liberty Bell.
See last lecture (Lecture 9A) for a guide!
Use OSMnx to download all amenities in Philadelphia of type "tourism".
ox.geometries_from_place()
can download OSM features with a specific tagox.geometries_from_place?
philly_tourism = ox.geometries_from_place("Philadelphia, PA", tags={"tourism": True})
len(philly_tourism)
philly_tourism.head()
You should notice we have the building footprint for the Art Museum (a polygon geometry) and the point location for the Liberty Bell.
.squeeze()
function can be useful for converting to a Series object from a DataFrame of length 1# How to find the name of the POI: search for keywords
philly_tourism.loc[philly_tourism['name'].str.contains("Art", na=False)]
art_museum = philly_tourism.query("name == 'Philadelphia Museum of Art'").squeeze()
art_museum.geometry
liberty_bell = philly_tourism.query("name == 'Liberty Bell'").squeeze()
liberty_bell.geometry
For the Art Museum geometry, we can use the .geometry.centroid
attribute to calculate the centroid of the building footprint.
Remember: we need the coordinates in the order of (latitude, longitude)
liberty_bell_x = liberty_bell.geometry.x
liberty_bell_y = liberty_bell.geometry.y
art_museum_x = art_museum.geometry.centroid.x
art_museum_y = art_museum.geometry.centroid.y
Use the street network graph around City Hall and the ox.get_nearest_node()
function to find the starting and ending nodes for the trip.
# Get the origin node
orig_node = ox.distance.nearest_nodes(G, liberty_bell_x, liberty_bell_y)
# Get the destination node
dest_node = ox.distance.nearest_nodes(G, art_museum_x, art_museum_y)
networkx
to find the shortest path between nodes¶The nx.shortest_path()
will do the calculation for you!
import networkx as nx
# Calculate the shortest path between these nodes
route = nx.shortest_path(G, orig_node, dest_node)
route
Now, we can overlay the shortest route between two nodes on the folium map.
Key function: use ox.plot_route_folium
to plot the route.
# plot the route with folium
route_map = ox.plot_route_folium(G, route)
filepath = 'route.html'
route_map.save(filepath)
IFrame(filepath, width=600, height=500)
We can also add the underlying street network graph
# plot the route with folium on top of the previously created graph_map
route_graph_map = ox.plot_route_folium(G, route, route_map=graph_map)
# save as html file then display map as an iframe
filepath = 'route_graph.html'
route_graph_map.save(filepath)
IFrame(filepath, width=600, height=500)
Note the Leaflet
annotation in the bottom right corner of the maps...
Things we'll cover:
import folium
Key function: folium.Map
Some key ones:
Let's take a look at the help message:
folium.Map?
# let's center the map on Philadelphia
m = folium.Map(
location=[39.99, -75.13],
zoom_start=11
)
m
m = folium.Map(
location=[39.99, -75.13],
zoom_start=11,
tiles='stamenwatercolor'
)
m
Let's try out the ESRI World Map:
Important: for custom tile providers, you need to specify the attribution too!
tile_url = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}'
attr = 'Tiles © Esri — Source: Esri, DeLorme, NAVTEQ, USGS, Intermap, iPC, NRCAN, Esri Japan, METI, Esri China (Hong Kong), Esri (Thailand), TomTom, 2012'
m = folium.Map(
location=[39.99, -75.13],
zoom_start=11,
tiles=tile_url,
attr=attr
)
m
Key function: folium.GeoJson
Key parameters:
style_function
: set the default style of the featureshighlight_function
: set the style when the mouse hovers over the features tooltip
: add a tooltip when hovering over a featurefolium.GeoJson?
folium.GeoJsonTooltip?
# Load neighborhoods from GitHub
url = "https://github.com/azavea/geo-data/raw/master/Neighborhoods_Philadelphia/Neighborhoods_Philadelphia.geojson"
hoods = gpd.read_file(url).rename(columns={"mapname": "neighborhood"})
# Load ZIP codes from Open Data Philly
zip_url = "http://data.phl.opendata.arcgis.com/datasets/b54ec5210cee41c3a884c9086f7af1be_0.geojson"
zip_codes = gpd.read_file(zip_url).rename(columns={"CODE":"ZIP Code"})
ax = ox.project_gdf(hoods).plot(fc="lightblue", ec="gray")
ax.set_axis_off()
ax = ox.project_gdf(zip_codes).plot(fc="lightblue", ec="gray")
ax.set_axis_off()
Define functions to set the styles:
def get_zip_code_style(feature):
"""Return a style dict."""
return {"weight": 2, "color": "white"}
def get_neighborhood_style(feature):
"""Return a style dict."""
return {"weight": 2, "color": "lightblue", "fillOpacity": 0.1}
def get_highlighted_style(feature):
"""Return a style dict when highlighting a feature."""
return {"weight": 2, "color": "red"}
# Create the map
m = folium.Map(
location=[39.99, -75.13],
tiles='Cartodb dark_matter',
zoom_start=11
)
# Add the ZIP Codes GeoJson to the map
folium.GeoJson(
zip_codes.to_crs(epsg=4326).to_json(), # IMPORTANT: make sure CRS is lat/lng (EPSG=4326)
name='Philadelphia ZIP_codes',
style_function=get_zip_code_style,
highlight_function=get_highlighted_style,
tooltip=folium.GeoJsonTooltip(['ZIP Code'])
).add_to(m)
# Add a SECOND layer for neighborhoods
folium.GeoJson(
hoods.to_crs(epsg=4326).to_json(), # IMPORTANT: make sure CRS is lat/lng (EPSG=4326)
name='Neighborhoods',
style_function=get_neighborhood_style,
highlight_function=get_highlighted_style,
tooltip=folium.GeoJsonTooltip(['neighborhood'])
).add_to(m)
# Also add option to toggle layers
folium.LayerControl().add_to(m)
m
.to_json()
LayerControl
to toggle different layers on the mapfolium.GeoJsonTooltip
Overlay GeoJSON features on an interactive map, colored by a specific data variable
In the interest of time, I've used cenpy
to download data for internet availability from the 2019 5-year ACS, but a good at-home exercise is to try to replicate my work.
census_data = pd.read_csv("./data/internet_avail_census.csv", dtype={"geoid": str})
# Remove counties with no households
valid = census_data['universe'] > 0
census_data = census_data.loc[valid]
# Calculate the percent without internet
census_data['percent_no_internet'] = census_data['no_internet'] / census_data['universe']
census_data.head()
Load counties from the data folder as well:
counties = gpd.read_file("./data/us-counties-10m.geojson")
counties.head()
folium.Choropleth?
Steps:
key_on=
), using the GeoJSON "features.properties." syntaxcolumns=
keywordm = folium.Map(location=[40, -98], zoom_start=4)
# Convert the counties geometries into GeoJSON
counties_geojson = counties.to_crs(epsg=4326).to_json()
folium.Choropleth(
geo_data=counties_geojson, # Pass in GeoJSON data for counties
data=census_data, # the census data
columns=["geoid", 'percent_no_internet'], # First column must be the key, second the values
key_on="feature.properties.id", # Key to match on in the geometries --> Remember to prepend "feature.properties"
fill_color='RdPu', # any ColorBrewer name will work here
fill_opacity=0.7,
line_opacity=1,
line_weight=0.5,
legend_name='Households without Internet (%)',
name='choropleth',
).add_to(m)
m