North America Roads¶
This example uses data from Natural Earth to plot the road network in North America. Refer to the data documentation for more information about this dataset.
You can view a hosted version of this notebook on Notebook Sharing Space (6MB download).
Dependencies¶
- lonboard
- pyogrio
Imports¶
import geopandas as gpd
import palettable.colorbrewer.diverging
from lonboard import Map, PathLayer
from lonboard.colormap import apply_continuous_cmap
The "public" URL for this dataset from the Natural Earth website is
https://www.naturalearthdata.com/http//www.naturalearthdata.com/download/10m/cultural/ne_10m_roads_north_america.zip
That doesn't appear to work directly inside a notebook, so we'll use the URL the above redirects to:
https://naciscdn.org/naturalearth/10m/cultural/ne_10m_roads_north_america.zip
It's possible this "private" URL will change in the future.
url = "https://naciscdn.org/naturalearth/10m/cultural/ne_10m_roads_north_america.zip"
We'll use GeoPandas to fetch this data (45MB) over the internet and load it into a GeoDataFrame
. This uses the pyogrio
engine, which is faster. Ensure you have pyogrio
installed.
gdf = gpd.read_file(url, engine="pyogrio")
This dataframe has a variety of attributes, plus a geometry column with a LineString
type.
gdf.head()
To ensure that this demo is snappy on most computers, we'll filter to only the contiguous U.S. If you're on a recent computer, feel free to comment out this line.
gdf = gdf[gdf["state"] == "California"]
To render LineString
data, first create a PathLayer
and then add it to a Map
object.
layer = PathLayer.from_geopandas(gdf, width_min_pixels=0.8)
map_ = Map(layer)
map_
We can look at the documentation for PathLayer
to see what other rendering options it allows. Let's set the path color to something other than black:
layer.get_color = [200, 0, 200]
Ok, so we can see the data! That's great! But let's customize the rendering based on an attribute!
The scalerank
column tells how important the road is in the road network. Let's see what the distribution of values is for this column:
gdf["scalerank"].value_counts().sort_index()
Ok, so the values range from 3
to 12
. To assign a colormap to this column, we need "normalized" values that span between 0 and 1:
normalized_scale_rank = (gdf["scalerank"] - 3) / 9
The values of this array now range from 0 to 1:
normalized_scale_rank.min(), normalized_scale_rank.max()
Let's select a colormap to apply to this data:
cmap = palettable.colorbrewer.diverging.PuOr_10
cmap.mpl_colormap
Now we'll use apply_continuous_cmap
onto this array to generate colors for our data. Just set this new array onto the existing layer, and you'll see the map update with the new colors!
layer.get_color = apply_continuous_cmap(
normalized_scale_rank, palettable.colorbrewer.diverging.PuOr_10, alpha=0.8
)