9. Geographic Plots

It is often useful to be able to relate datasets with their real-world context. You can plot geographic data just like any other type of data, as in the Texas Unemployment example, but Bokeh also provides several specialized mechanisms for plotting data in geographic coordinates:

from bokeh.io import output_notebook, show
from bokeh.plotting import figure
# nbi:hide_out
# Make all outputs INLINE for default (why a hell this is needed !!!)
output_notebook()
Loading BokehJS ...

WMTS Tile Source

WTMS is the most common web standard for tiled map data, i.e. maps supplied as standard-sized image patches from which the overall map can be constructed at a given zoom level. WTMS uses Web Mercator format, measuring distances from Greenwich, England as meters north and meters west, which is easy to compute but does distort the global shape.

First let's create an empty Bokeh plot covering the USA, with bounds specified in meters:

from bokeh.plotting import figure
from bokeh.models import WMTSTileSource

# web mercator coordinates
USA = x_range,y_range = (
    (-13884029,-7453304),
    (2698291,6455972)
)

p = figure(
    plot_width=800,
    tools='pan, wheel_zoom, reset',
    x_range=x_range,
    y_range=y_range, 
    x_axis_type="mercator",
    y_axis_type="mercator")

A few WTMS tile sources are already defined in bokeh.tile_providers, but here we'll show how to specify the interface using a format string showing Bokeh how to request a tile with the required zoom, x, and y values from a given tile provider:

url = 'http://a.basemaps.cartocdn.com/rastertiles/voyager/{Z}/{X}/{Y}.png'
attribution = "Tiles by Carto, under CC BY 3.0. Data by OSM, under ODbL"

p.add_tile(WMTSTileSource(url=url, attribution=attribution))
TileRenderer(
id = '1036', …)

If you show the figure, you can then use the wheel zoom and pan tools to navigate over any zoom level, and Bokeh will request the appropriate tiles from the server and insert them at the correct locations in the plot:

# show the results
show(p)

That's all it takes to put map data into your plot! Of course, you'll usually want to show other data as well, or you could just use the tile server's own web address. You can now add anything you would normally use in a Bokeh plot, as long as you can obtain coordinates for it in Web Mercator format. For example:

import pandas as pd
import numpy as np

def wgs84_to_web_mercator(df, lon="lon", lat="lat"):
    """Converts decimal longitude/latitude to Web Mercator format"""
    k = 6378137
    df["x"] = df[lon] * (k * np.pi/180.0)
    df["y"] = np.log(np.tan((90 + df[lat]) * np.pi/360.0)) * k
    return df

df = pd.DataFrame(dict(name=["Austin", "NYC"], lon=[-97.7431,-74.0059], lat=[30.2672,40.7128]))
wgs84_to_web_mercator(df)
name lon lat x y
0 Austin -97.7431 30.2672 -1.088071e+07 3.537942e+06
1 NYC -74.0059 40.7128 -8.238299e+06 4.970072e+06
p = figure(
    plot_width=800,
    tools='pan, wheel_zoom, reset',
    x_range=x_range,
    y_range=y_range, 
    x_axis_type="mercator",
    y_axis_type="mercator"
)

p.add_tile(
    WMTSTileSource(
        url=url,
        attribution=attribution
    )
)

p.circle(
    x=df['x'],
    y=df['y'],
    fill_color='orange',
    size=10
)

# show the results
show(p)