{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n", " \n", " \n", " \n", " \n", "
\n", " \n", " \n", " \n", " \n", "

Bokeh Tutorial

\n", "
\n", "\n", "

09. Geographic Plots

" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "
\n", " \n", " Loading BokehJS ...\n", "
" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/javascript": [ "\n", "(function(root) {\n", " function now() {\n", " return new Date();\n", " }\n", "\n", " var force = true;\n", "\n", " if (typeof root._bokeh_onload_callbacks === \"undefined\" || force === true) {\n", " root._bokeh_onload_callbacks = [];\n", " root._bokeh_is_loading = undefined;\n", " }\n", "\n", " var JS_MIME_TYPE = 'application/javascript';\n", " var HTML_MIME_TYPE = 'text/html';\n", " var EXEC_MIME_TYPE = 'application/vnd.bokehjs_exec.v0+json';\n", " var CLASS_NAME = 'output_bokeh rendered_html';\n", "\n", " /**\n", " * Render data to the DOM node\n", " */\n", " function render(props, node) {\n", " var script = document.createElement(\"script\");\n", " node.appendChild(script);\n", " }\n", "\n", " /**\n", " * Handle when an output is cleared or removed\n", " */\n", " function handleClearOutput(event, handle) {\n", " var cell = handle.cell;\n", "\n", " var id = cell.output_area._bokeh_element_id;\n", " var server_id = cell.output_area._bokeh_server_id;\n", " // Clean up Bokeh references\n", " if (id != null && id in Bokeh.index) {\n", " Bokeh.index[id].model.document.clear();\n", " delete Bokeh.index[id];\n", " }\n", "\n", " if (server_id !== undefined) {\n", " // Clean up Bokeh references\n", " var cmd = \"from bokeh.io.state import curstate; print(curstate().uuid_to_server['\" + server_id + \"'].get_sessions()[0].document.roots[0]._id)\";\n", " cell.notebook.kernel.execute(cmd, {\n", " iopub: {\n", " output: function(msg) {\n", " var id = msg.content.text.trim();\n", " if (id in Bokeh.index) {\n", " Bokeh.index[id].model.document.clear();\n", " delete Bokeh.index[id];\n", " }\n", " }\n", " }\n", " });\n", " // Destroy server and session\n", " var cmd = \"import bokeh.io.notebook as ion; ion.destroy_server('\" + server_id + \"')\";\n", " cell.notebook.kernel.execute(cmd);\n", " }\n", " }\n", "\n", " /**\n", " * Handle when a new output is added\n", " */\n", " function handleAddOutput(event, handle) {\n", " var output_area = handle.output_area;\n", " var output = handle.output;\n", "\n", " // limit handleAddOutput to display_data with EXEC_MIME_TYPE content only\n", " if ((output.output_type != \"display_data\") || (!output.data.hasOwnProperty(EXEC_MIME_TYPE))) {\n", " return\n", " }\n", "\n", " var toinsert = output_area.element.find(\".\" + CLASS_NAME.split(' ')[0]);\n", "\n", " if (output.metadata[EXEC_MIME_TYPE][\"id\"] !== undefined) {\n", " toinsert[toinsert.length - 1].firstChild.textContent = output.data[JS_MIME_TYPE];\n", " // store reference to embed id on output_area\n", " output_area._bokeh_element_id = output.metadata[EXEC_MIME_TYPE][\"id\"];\n", " }\n", " if (output.metadata[EXEC_MIME_TYPE][\"server_id\"] !== undefined) {\n", " var bk_div = document.createElement(\"div\");\n", " bk_div.innerHTML = output.data[HTML_MIME_TYPE];\n", " var script_attrs = bk_div.children[0].attributes;\n", " for (var i = 0; i < script_attrs.length; i++) {\n", " toinsert[toinsert.length - 1].firstChild.setAttribute(script_attrs[i].name, script_attrs[i].value);\n", " toinsert[toinsert.length - 1].firstChild.textContent = bk_div.children[0].textContent\n", " }\n", " // store reference to server id on output_area\n", " output_area._bokeh_server_id = output.metadata[EXEC_MIME_TYPE][\"server_id\"];\n", " }\n", " }\n", "\n", " function register_renderer(events, OutputArea) {\n", "\n", " function append_mime(data, metadata, element) {\n", " // create a DOM node to render to\n", " var toinsert = this.create_output_subarea(\n", " metadata,\n", " CLASS_NAME,\n", " EXEC_MIME_TYPE\n", " );\n", " this.keyboard_manager.register_events(toinsert);\n", " // Render to node\n", " var props = {data: data, metadata: metadata[EXEC_MIME_TYPE]};\n", " render(props, toinsert[toinsert.length - 1]);\n", " element.append(toinsert);\n", " return toinsert\n", " }\n", "\n", " /* Handle when an output is cleared or removed */\n", " events.on('clear_output.CodeCell', handleClearOutput);\n", " events.on('delete.Cell', handleClearOutput);\n", "\n", " /* Handle when a new output is added */\n", " events.on('output_added.OutputArea', handleAddOutput);\n", "\n", " /**\n", " * Register the mime type and append_mime function with output_area\n", " */\n", " OutputArea.prototype.register_mime_type(EXEC_MIME_TYPE, append_mime, {\n", " /* Is output safe? */\n", " safe: true,\n", " /* Index of renderer in `output_area.display_order` */\n", " index: 0\n", " });\n", " }\n", "\n", " // register the mime type if in Jupyter Notebook environment and previously unregistered\n", " if (root.Jupyter !== undefined) {\n", " var events = require('base/js/events');\n", " var OutputArea = require('notebook/js/outputarea').OutputArea;\n", "\n", " if (OutputArea.prototype.mime_types().indexOf(EXEC_MIME_TYPE) == -1) {\n", " register_renderer(events, OutputArea);\n", " }\n", " }\n", "\n", " \n", " if (typeof (root._bokeh_timeout) === \"undefined\" || force === true) {\n", " root._bokeh_timeout = Date.now() + 5000;\n", " root._bokeh_failed_load = false;\n", " }\n", "\n", " var NB_LOAD_WARNING = {'data': {'text/html':\n", " \"
\\n\"+\n", " \"

\\n\"+\n", " \"BokehJS does not appear to have successfully loaded. If loading BokehJS from CDN, this \\n\"+\n", " \"may be due to a slow or bad network connection. Possible fixes:\\n\"+\n", " \"

\\n\"+\n", " \"\\n\"+\n", " \"\\n\"+\n", " \"from bokeh.resources import INLINE\\n\"+\n", " \"output_notebook(resources=INLINE)\\n\"+\n", " \"\\n\"+\n", " \"
\"}};\n", "\n", " function display_loaded() {\n", " var el = document.getElementById(\"1001\");\n", " if (el != null) {\n", " el.textContent = \"BokehJS is loading...\";\n", " }\n", " if (root.Bokeh !== undefined) {\n", " if (el != null) {\n", " el.textContent = \"BokehJS \" + root.Bokeh.version + \" successfully loaded.\";\n", " }\n", " } else if (Date.now() < root._bokeh_timeout) {\n", " setTimeout(display_loaded, 100)\n", " }\n", " }\n", "\n", "\n", " function run_callbacks() {\n", " try {\n", " root._bokeh_onload_callbacks.forEach(function(callback) {\n", " if (callback != null)\n", " callback();\n", " });\n", " } finally {\n", " delete root._bokeh_onload_callbacks\n", " }\n", " console.debug(\"Bokeh: all callbacks have finished\");\n", " }\n", "\n", " function load_libs(css_urls, js_urls, callback) {\n", " if (css_urls == null) css_urls = [];\n", " if (js_urls == null) js_urls = [];\n", "\n", " root._bokeh_onload_callbacks.push(callback);\n", " if (root._bokeh_is_loading > 0) {\n", " console.debug(\"Bokeh: BokehJS is being loaded, scheduling callback at\", now());\n", " return null;\n", " }\n", " if (js_urls == null || js_urls.length === 0) {\n", " run_callbacks();\n", " return null;\n", " }\n", " console.debug(\"Bokeh: BokehJS not loaded, scheduling load and callback at\", now());\n", " root._bokeh_is_loading = css_urls.length + js_urls.length;\n", "\n", " function on_load() {\n", " root._bokeh_is_loading--;\n", " if (root._bokeh_is_loading === 0) {\n", " console.debug(\"Bokeh: all BokehJS libraries/stylesheets loaded\");\n", " run_callbacks()\n", " }\n", " }\n", "\n", " function on_error() {\n", " console.error(\"failed to load \" + url);\n", " }\n", "\n", " for (var i = 0; i < css_urls.length; i++) {\n", " var url = css_urls[i];\n", " const element = document.createElement(\"link\");\n", " element.onload = on_load;\n", " element.onerror = on_error;\n", " element.rel = \"stylesheet\";\n", " element.type = \"text/css\";\n", " element.href = url;\n", " console.debug(\"Bokeh: injecting link tag for BokehJS stylesheet: \", url);\n", " document.body.appendChild(element);\n", " }\n", "\n", " const hashes = {\"https://cdn.bokeh.org/bokeh/release/bokeh-2.0.1.min.js\": \"JpP8FXbgAZLkfur7LiK3j9AGBhHNIvF742meBJrjO2ShJDhCG2I1uVvW+0DUtrmc\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.0.1.min.js\": \"xZlADit0Q04ISQEdKg2k3L4W9AwQBAuDs9nJL9fM/WwzL1tEU9VPNezOFX0nLEAz\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.0.1.min.js\": \"4BuPRZkdMKSnj3zoxiNrQ86XgNw0rYmBOxe7nshquXwwcauupgBF2DHLVG1WuZlV\", \"https://cdn.bokeh.org/bokeh/release/bokeh-gl-2.0.1.min.js\": \"Dv1SQ87hmDqK6S5OhBf0bCuwAEvL5QYL0PuR/F1SPVhCS/r/abjkbpKDYL2zeM19\"};\n", "\n", " for (var i = 0; i < js_urls.length; i++) {\n", " var url = js_urls[i];\n", " var element = document.createElement('script');\n", " element.onload = on_load;\n", " element.onerror = on_error;\n", " element.async = false;\n", " element.src = url;\n", " if (url in hashes) {\n", " element.crossOrigin = \"anonymous\";\n", " element.integrity = \"sha384-\" + hashes[url];\n", " }\n", " console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n", " document.head.appendChild(element);\n", " }\n", " };var element = document.getElementById(\"1001\");\n", " if (element == null) {\n", " console.error(\"Bokeh: ERROR: autoload.js configured with elementid '1001' but no matching script tag was found. \")\n", " return false;\n", " }\n", "\n", " function inject_raw_css(css) {\n", " const element = document.createElement(\"style\");\n", " element.appendChild(document.createTextNode(css));\n", " document.body.appendChild(element);\n", " }\n", "\n", " \n", " var js_urls = [\"https://cdn.bokeh.org/bokeh/release/bokeh-2.0.1.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.0.1.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.0.1.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-gl-2.0.1.min.js\"];\n", " var css_urls = [];\n", " \n", "\n", " var inline_js = [\n", " function(Bokeh) {\n", " Bokeh.set_log_level(\"info\");\n", " },\n", " function(Bokeh) {\n", " \n", " \n", " }\n", " ];\n", "\n", " function run_inline_js() {\n", " \n", " if (root.Bokeh !== undefined || force === true) {\n", " \n", " for (var i = 0; i < inline_js.length; i++) {\n", " inline_js[i].call(root, root.Bokeh);\n", " }\n", " if (force === true) {\n", " display_loaded();\n", " }} else if (Date.now() < root._bokeh_timeout) {\n", " setTimeout(run_inline_js, 100);\n", " } else if (!root._bokeh_failed_load) {\n", " console.log(\"Bokeh: BokehJS failed to load within specified timeout.\");\n", " root._bokeh_failed_load = true;\n", " } else if (force !== true) {\n", " var cell = $(document.getElementById(\"1001\")).parents('.cell').data().cell;\n", " cell.output_area.append_execute_result(NB_LOAD_WARNING)\n", " }\n", "\n", " }\n", "\n", " if (root._bokeh_is_loading === 0) {\n", " console.debug(\"Bokeh: BokehJS loaded, going straight to plotting\");\n", " run_inline_js();\n", " } else {\n", " load_libs(css_urls, js_urls, function() {\n", " console.debug(\"Bokeh: BokehJS plotting callback run at\", now());\n", " run_inline_js();\n", " });\n", " }\n", "}(window));" ], "application/vnd.bokehjs_load.v0+json": "\n(function(root) {\n function now() {\n return new Date();\n }\n\n var force = true;\n\n if (typeof root._bokeh_onload_callbacks === \"undefined\" || force === true) {\n root._bokeh_onload_callbacks = [];\n root._bokeh_is_loading = undefined;\n }\n\n \n\n \n if (typeof (root._bokeh_timeout) === \"undefined\" || force === true) {\n root._bokeh_timeout = Date.now() + 5000;\n root._bokeh_failed_load = false;\n }\n\n var NB_LOAD_WARNING = {'data': {'text/html':\n \"
\\n\"+\n \"

\\n\"+\n \"BokehJS does not appear to have successfully loaded. If loading BokehJS from CDN, this \\n\"+\n \"may be due to a slow or bad network connection. Possible fixes:\\n\"+\n \"

\\n\"+\n \"\\n\"+\n \"\\n\"+\n \"from bokeh.resources import INLINE\\n\"+\n \"output_notebook(resources=INLINE)\\n\"+\n \"\\n\"+\n \"
\"}};\n\n function display_loaded() {\n var el = document.getElementById(\"1001\");\n if (el != null) {\n el.textContent = \"BokehJS is loading...\";\n }\n if (root.Bokeh !== undefined) {\n if (el != null) {\n el.textContent = \"BokehJS \" + root.Bokeh.version + \" successfully loaded.\";\n }\n } else if (Date.now() < root._bokeh_timeout) {\n setTimeout(display_loaded, 100)\n }\n }\n\n\n function run_callbacks() {\n try {\n root._bokeh_onload_callbacks.forEach(function(callback) {\n if (callback != null)\n callback();\n });\n } finally {\n delete root._bokeh_onload_callbacks\n }\n console.debug(\"Bokeh: all callbacks have finished\");\n }\n\n function load_libs(css_urls, js_urls, callback) {\n if (css_urls == null) css_urls = [];\n if (js_urls == null) js_urls = [];\n\n root._bokeh_onload_callbacks.push(callback);\n if (root._bokeh_is_loading > 0) {\n console.debug(\"Bokeh: BokehJS is being loaded, scheduling callback at\", now());\n return null;\n }\n if (js_urls == null || js_urls.length === 0) {\n run_callbacks();\n return null;\n }\n console.debug(\"Bokeh: BokehJS not loaded, scheduling load and callback at\", now());\n root._bokeh_is_loading = css_urls.length + js_urls.length;\n\n function on_load() {\n root._bokeh_is_loading--;\n if (root._bokeh_is_loading === 0) {\n console.debug(\"Bokeh: all BokehJS libraries/stylesheets loaded\");\n run_callbacks()\n }\n }\n\n function on_error() {\n console.error(\"failed to load \" + url);\n }\n\n for (var i = 0; i < css_urls.length; i++) {\n var url = css_urls[i];\n const element = document.createElement(\"link\");\n element.onload = on_load;\n element.onerror = on_error;\n element.rel = \"stylesheet\";\n element.type = \"text/css\";\n element.href = url;\n console.debug(\"Bokeh: injecting link tag for BokehJS stylesheet: \", url);\n document.body.appendChild(element);\n }\n\n const hashes = {\"https://cdn.bokeh.org/bokeh/release/bokeh-2.0.1.min.js\": \"JpP8FXbgAZLkfur7LiK3j9AGBhHNIvF742meBJrjO2ShJDhCG2I1uVvW+0DUtrmc\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.0.1.min.js\": \"xZlADit0Q04ISQEdKg2k3L4W9AwQBAuDs9nJL9fM/WwzL1tEU9VPNezOFX0nLEAz\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.0.1.min.js\": \"4BuPRZkdMKSnj3zoxiNrQ86XgNw0rYmBOxe7nshquXwwcauupgBF2DHLVG1WuZlV\", \"https://cdn.bokeh.org/bokeh/release/bokeh-gl-2.0.1.min.js\": \"Dv1SQ87hmDqK6S5OhBf0bCuwAEvL5QYL0PuR/F1SPVhCS/r/abjkbpKDYL2zeM19\"};\n\n for (var i = 0; i < js_urls.length; i++) {\n var url = js_urls[i];\n var element = document.createElement('script');\n element.onload = on_load;\n element.onerror = on_error;\n element.async = false;\n element.src = url;\n if (url in hashes) {\n element.crossOrigin = \"anonymous\";\n element.integrity = \"sha384-\" + hashes[url];\n }\n console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n document.head.appendChild(element);\n }\n };var element = document.getElementById(\"1001\");\n if (element == null) {\n console.error(\"Bokeh: ERROR: autoload.js configured with elementid '1001' but no matching script tag was found. \")\n return false;\n }\n\n function inject_raw_css(css) {\n const element = document.createElement(\"style\");\n element.appendChild(document.createTextNode(css));\n document.body.appendChild(element);\n }\n\n \n var js_urls = [\"https://cdn.bokeh.org/bokeh/release/bokeh-2.0.1.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.0.1.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.0.1.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-gl-2.0.1.min.js\"];\n var css_urls = [];\n \n\n var inline_js = [\n function(Bokeh) {\n Bokeh.set_log_level(\"info\");\n },\n function(Bokeh) {\n \n \n }\n ];\n\n function run_inline_js() {\n \n if (root.Bokeh !== undefined || force === true) {\n \n for (var i = 0; i < inline_js.length; i++) {\n inline_js[i].call(root, root.Bokeh);\n }\n if (force === true) {\n display_loaded();\n }} else if (Date.now() < root._bokeh_timeout) {\n setTimeout(run_inline_js, 100);\n } else if (!root._bokeh_failed_load) {\n console.log(\"Bokeh: BokehJS failed to load within specified timeout.\");\n root._bokeh_failed_load = true;\n } else if (force !== true) {\n var cell = $(document.getElementById(\"1001\")).parents('.cell').data().cell;\n cell.output_area.append_execute_result(NB_LOAD_WARNING)\n }\n\n }\n\n if (root._bokeh_is_loading === 0) {\n console.debug(\"Bokeh: BokehJS loaded, going straight to plotting\");\n run_inline_js();\n } else {\n load_libs(css_urls, js_urls, function() {\n console.debug(\"Bokeh: BokehJS plotting callback run at\", now());\n run_inline_js();\n });\n }\n}(window));" }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from bokeh.io import output_notebook, show\n", "output_notebook()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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](https://docs.bokeh.org/en/latest/docs/gallery/texas.html), but Bokeh also Bokeh provides several specialized mechanisms for plotting data in geographic coordinates:\n", "\n", "* [GMapPlot](https://docs.bokeh.org/en/latest/docs/user_guide/geo.html#google-maps-support): Bokeh Plots on top of Google Maps\n", "\n", "* [TileSource](https://docs.bokeh.org/en/latest/docs/user_guide/geo.html#tile-providers), especially WMTSTileSource: allows data to be overlaid on data from any map tile server, including \n", "[Google Maps](http://maps.google.com), \n", "[Stamen](http://maps.stamen.com), \n", "[MapQuest](https://www.mapquest.com/), \n", "[OpenStreetMap](https://www.openstreetmap.org), \n", "[ESRI](http://www.esri.com), \n", "and custom servers.\n", "\n", "* [GeoJSONDataSource](https://docs.bokeh.org/en/latest/docs/user_guide/geo.html#geojson-datasource): Allows reading data in [GeoJSON](http://geojson.org/) format for use with Bokeh plots and glyphs, similar to `ColumnDataSource`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Google Maps plots\n", "\n", "Bokeh can render its own interactive glyphs on top of a Google Maps underlay. To use this functionality, call the `gmap` method on a standard figure as shown below. You will need to supply a valid Google API key for the plot to function, see: https://developers.google.com/maps/documentation/javascript/get-api-key" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "\n", "
\n" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/javascript": [ "(function(root) {\n", " function embed_document(root) {\n", " \n", " var docs_json = {\"2e5a84df-881d-461d-be5b-4c72a50c312a\":{\"roots\":{\"references\":[{\"attributes\":{\"api_key\":\"QUl6YVN5QU0xT0hWbTZZcl9pNTRLdDAxbXlsZnh5TnhRZHhteEhR\",\"below\":[{\"id\":\"1013\"}],\"left\":[{\"id\":\"1018\"}],\"map_options\":{\"id\":\"1003\"},\"renderers\":[{\"id\":\"1034\"}],\"title\":{\"id\":\"1005\"},\"toolbar\":{\"id\":\"1025\"},\"x_range\":{\"id\":\"1006\"},\"x_scale\":{\"id\":\"1037\"},\"y_range\":{\"id\":\"1007\"},\"y_scale\":{\"id\":\"1036\"}},\"id\":\"1004\",\"subtype\":\"GMap\",\"type\":\"GMapPlot\"},{\"attributes\":{},\"id\":\"1006\",\"type\":\"Range1d\"},{\"attributes\":{\"formatter\":{\"id\":\"1011\"},\"ticker\":{\"id\":\"1012\"}},\"id\":\"1013\",\"type\":\"LinearAxis\"},{\"attributes\":{\"source\":{\"id\":\"1030\"}},\"id\":\"1035\",\"type\":\"CDSView\"},{\"attributes\":{},\"id\":\"1023\",\"type\":\"ResetTool\"},{\"attributes\":{},\"id\":\"1040\",\"type\":\"UnionRenderers\"},{\"attributes\":{\"dimension\":\"lat\"},\"id\":\"1017\",\"type\":\"MercatorTicker\"},{\"attributes\":{\"formatter\":{\"id\":\"1016\"},\"ticker\":{\"id\":\"1017\"}},\"id\":\"1018\",\"type\":\"LinearAxis\"},{\"attributes\":{\"dimension\":\"lon\"},\"id\":\"1012\",\"type\":\"MercatorTicker\"},{\"attributes\":{\"fill_alpha\":{\"value\":0.8},\"fill_color\":{\"value\":\"blue\"},\"line_color\":{\"value\":\"#1f77b4\"},\"size\":{\"units\":\"screen\",\"value\":15},\"x\":{\"field\":\"lon\"},\"y\":{\"field\":\"lat\"}},\"id\":\"1032\",\"type\":\"Circle\"},{\"attributes\":{},\"id\":\"1021\",\"type\":\"PanTool\"},{\"attributes\":{\"dimension\":\"lat\"},\"id\":\"1016\",\"type\":\"MercatorTickFormatter\"},{\"attributes\":{},\"id\":\"1007\",\"type\":\"Range1d\"},{\"attributes\":{\"active_drag\":\"auto\",\"active_inspect\":\"auto\",\"active_multi\":null,\"active_scroll\":\"auto\",\"active_tap\":\"auto\",\"tools\":[{\"id\":\"1021\"},{\"id\":\"1022\"},{\"id\":\"1023\"},{\"id\":\"1024\"}]},\"id\":\"1025\",\"type\":\"Toolbar\"},{\"attributes\":{\"lat\":30.2861,\"lng\":-97.7394,\"zoom\":11},\"id\":\"1003\",\"type\":\"GMapOptions\"},{\"attributes\":{},\"id\":\"1024\",\"type\":\"HelpTool\"},{\"attributes\":{\"data\":{\"lat\":[30.29,30.2,30.29],\"lon\":[-97.7,-97.74,-97.78]},\"selected\":{\"id\":\"1039\"},\"selection_policy\":{\"id\":\"1040\"}},\"id\":\"1030\",\"type\":\"ColumnDataSource\"},{\"attributes\":{},\"id\":\"1022\",\"type\":\"WheelZoomTool\"},{\"attributes\":{\"text\":\"Austin\"},\"id\":\"1005\",\"type\":\"Title\"},{\"attributes\":{},\"id\":\"1036\",\"type\":\"LinearScale\"},{\"attributes\":{\"dimension\":\"lon\"},\"id\":\"1011\",\"type\":\"MercatorTickFormatter\"},{\"attributes\":{},\"id\":\"1037\",\"type\":\"LinearScale\"},{\"attributes\":{\"data_source\":{\"id\":\"1030\"},\"glyph\":{\"id\":\"1032\"},\"hover_glyph\":null,\"muted_glyph\":null,\"nonselection_glyph\":{\"id\":\"1033\"},\"selection_glyph\":null,\"view\":{\"id\":\"1035\"}},\"id\":\"1034\",\"type\":\"GlyphRenderer\"},{\"attributes\":{\"fill_alpha\":{\"value\":0.1},\"fill_color\":{\"value\":\"blue\"},\"line_alpha\":{\"value\":0.1},\"line_color\":{\"value\":\"#1f77b4\"},\"size\":{\"units\":\"screen\",\"value\":15},\"x\":{\"field\":\"lon\"},\"y\":{\"field\":\"lat\"}},\"id\":\"1033\",\"type\":\"Circle\"},{\"attributes\":{},\"id\":\"1039\",\"type\":\"Selection\"}],\"root_ids\":[\"1004\"]},\"title\":\"Bokeh Application\",\"version\":\"2.0.1\"}};\n", " var render_items = [{\"docid\":\"2e5a84df-881d-461d-be5b-4c72a50c312a\",\"root_ids\":[\"1004\"],\"roots\":{\"1004\":\"7bd20ebd-caf2-4919-ad73-ccbdce28eecb\"}}];\n", " root.Bokeh.embed.embed_items_notebook(docs_json, render_items);\n", "\n", " }\n", " if (root.Bokeh !== undefined) {\n", " embed_document(root);\n", " } else {\n", " var attempts = 0;\n", " var timer = setInterval(function(root) {\n", " if (root.Bokeh !== undefined) {\n", " clearInterval(timer);\n", " embed_document(root);\n", " } else {\n", " attempts++;\n", " if (attempts > 100) {\n", " clearInterval(timer);\n", " console.log(\"Bokeh: ERROR: Unable to run BokehJS code because BokehJS library is missing\");\n", " }\n", " }\n", " }, 10, root)\n", " }\n", "})(window);" ], "application/vnd.bokehjs_exec.v0+json": "" }, "metadata": { "application/vnd.bokehjs_exec.v0+json": { "id": "1004" } }, "output_type": "display_data" } ], "source": [ "import os\n", "from bokeh.models import GMapOptions\n", "from bokeh.plotting import gmap\n", "\n", "map_options = GMapOptions(lat=30.2861, lng=-97.7394, map_type=\"roadmap\", zoom=11)\n", "\n", "# Replace the value below with your personal API key:\n", "api_key = os.environ[\"GOOGLE_API_KEY\"]\n", "\n", "p = gmap(api_key, map_options, title=\"Austin\")\n", "\n", "data = dict(lat=[ 30.29, 30.20, 30.29],\n", " lon=[-97.70, -97.74, -97.78])\n", "\n", "p.circle(x=\"lon\", y=\"lat\", size=15, fill_color=\"blue\", fill_alpha=0.8, source=data)\n", "\n", "show(p)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## WMTS Tile Source\n", "\n", "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. \n", "\n", "First let's create an empty Bokeh plot covering the USA, with bounds specified in meters:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "from bokeh.plotting import figure\n", "from bokeh.models import WMTSTileSource\n", "\n", "# web mercator coordinates\n", "USA = x_range,y_range = ((-13884029,-7453304), (2698291,6455972))\n", "\n", "p = figure(tools='pan, wheel_zoom', x_range=x_range, y_range=y_range, \n", " x_axis_type=\"mercator\", y_axis_type=\"mercator\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
TileRenderer(
id = '1110', …)
alpha = 1.0,
js_event_callbacks = {},
js_property_callbacks = {},
level = 'glyph',
name = None,
render_parents = True,
smoothing = True,
subscribed_events = [],
tags = [],
tile_source = WMTSTileSource(id='1109', ...),
visible = True,
x_range_name = 'default',
y_range_name = 'default')
\n", "\n" ], "text/plain": [ "TileRenderer(id='1110', ...)" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "url = 'http://a.basemaps.cartocdn.com/rastertiles/voyager/{Z}/{X}/{Y}.png'\n", "attribution = \"Tiles by Carto, under CC BY 3.0. Data by OSM, under ODbL\"\n", "\n", "p.add_tile(WMTSTileSource(url=url, attribution=attribution))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "\n", "
\n" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/javascript": [ "(function(root) {\n", " function embed_document(root) {\n", " \n", " var docs_json = {\"7f0acfd7-cdb6-45a7-8a52-b6cbdd932ddb\":{\"roots\":{\"references\":[{\"attributes\":{\"below\":[{\"id\":\"1088\"}],\"center\":[{\"id\":\"1095\"},{\"id\":\"1103\"}],\"left\":[{\"id\":\"1096\"}],\"renderers\":[{\"id\":\"1110\"}],\"title\":{\"id\":\"1119\"},\"toolbar\":{\"id\":\"1106\"},\"x_range\":{\"id\":\"1080\"},\"x_scale\":{\"id\":\"1084\"},\"y_range\":{\"id\":\"1082\"},\"y_scale\":{\"id\":\"1086\"}},\"id\":\"1079\",\"subtype\":\"Figure\",\"type\":\"Plot\"},{\"attributes\":{\"end\":6455972,\"start\":2698291},\"id\":\"1082\",\"type\":\"Range1d\"},{\"attributes\":{\"dimension\":\"lat\"},\"id\":\"1099\",\"type\":\"MercatorTickFormatter\"},{\"attributes\":{\"axis\":{\"id\":\"1088\"},\"ticker\":null},\"id\":\"1095\",\"type\":\"Grid\"},{\"attributes\":{\"dimension\":\"lat\"},\"id\":\"1097\",\"type\":\"MercatorTicker\"},{\"attributes\":{\"dimension\":\"lon\"},\"id\":\"1091\",\"type\":\"MercatorTickFormatter\"},{\"attributes\":{\"end\":-7453304,\"start\":-13884029},\"id\":\"1080\",\"type\":\"Range1d\"},{\"attributes\":{\"active_drag\":\"auto\",\"active_inspect\":\"auto\",\"active_multi\":null,\"active_scroll\":\"auto\",\"active_tap\":\"auto\",\"tools\":[{\"id\":\"1104\"},{\"id\":\"1105\"}]},\"id\":\"1106\",\"type\":\"Toolbar\"},{\"attributes\":{\"formatter\":{\"id\":\"1099\"},\"ticker\":{\"id\":\"1097\"}},\"id\":\"1096\",\"type\":\"MercatorAxis\"},{\"attributes\":{},\"id\":\"1084\",\"type\":\"LinearScale\"},{\"attributes\":{\"axis\":{\"id\":\"1096\"},\"dimension\":1,\"ticker\":null},\"id\":\"1103\",\"type\":\"Grid\"},{\"attributes\":{\"tile_source\":{\"id\":\"1109\"}},\"id\":\"1110\",\"type\":\"TileRenderer\"},{\"attributes\":{\"formatter\":{\"id\":\"1091\"},\"ticker\":{\"id\":\"1089\"}},\"id\":\"1088\",\"type\":\"MercatorAxis\"},{\"attributes\":{},\"id\":\"1105\",\"type\":\"WheelZoomTool\"},{\"attributes\":{},\"id\":\"1086\",\"type\":\"LinearScale\"},{\"attributes\":{\"attribution\":\"Tiles by Carto, under CC BY 3.0. Data by OSM, under ODbL\",\"url\":\"http://a.basemaps.cartocdn.com/rastertiles/voyager/{Z}/{X}/{Y}.png\"},\"id\":\"1109\",\"type\":\"WMTSTileSource\"},{\"attributes\":{\"dimension\":\"lon\"},\"id\":\"1089\",\"type\":\"MercatorTicker\"},{\"attributes\":{\"text\":\"\"},\"id\":\"1119\",\"type\":\"Title\"},{\"attributes\":{},\"id\":\"1104\",\"type\":\"PanTool\"}],\"root_ids\":[\"1079\"]},\"title\":\"Bokeh Application\",\"version\":\"2.0.1\"}};\n", " var render_items = [{\"docid\":\"7f0acfd7-cdb6-45a7-8a52-b6cbdd932ddb\",\"root_ids\":[\"1079\"],\"roots\":{\"1079\":\"4d2049cc-aaab-442a-a2c9-22f6965c2a0c\"}}];\n", " root.Bokeh.embed.embed_items_notebook(docs_json, render_items);\n", "\n", " }\n", " if (root.Bokeh !== undefined) {\n", " embed_document(root);\n", " } else {\n", " var attempts = 0;\n", " var timer = setInterval(function(root) {\n", " if (root.Bokeh !== undefined) {\n", " clearInterval(timer);\n", " embed_document(root);\n", " } else {\n", " attempts++;\n", " if (attempts > 100) {\n", " clearInterval(timer);\n", " console.log(\"Bokeh: ERROR: Unable to run BokehJS code because BokehJS library is missing\");\n", " }\n", " }\n", " }, 10, root)\n", " }\n", "})(window);" ], "application/vnd.bokehjs_exec.v0+json": "" }, "metadata": { "application/vnd.bokehjs_exec.v0+json": { "id": "1079" } }, "output_type": "display_data" } ], "source": [ "show(p)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
namelonlatxy
0Austin-97.743130.2672-1.088071e+073.537942e+06
1NYC-74.005940.7128-8.238299e+064.970072e+06
\n", "
" ], "text/plain": [ " name lon lat x y\n", "0 Austin -97.7431 30.2672 -1.088071e+07 3.537942e+06\n", "1 NYC -74.0059 40.7128 -8.238299e+06 4.970072e+06" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pandas as pd\n", "import numpy as np\n", "\n", "def wgs84_to_web_mercator(df, lon=\"lon\", lat=\"lat\"):\n", " \"\"\"Converts decimal longitude/latitude to Web Mercator format\"\"\"\n", " k = 6378137\n", " df[\"x\"] = df[lon] * (k * np.pi/180.0)\n", " df[\"y\"] = np.log(np.tan((90 + df[lat]) * np.pi/360.0)) * k\n", " return df\n", "\n", "df = pd.DataFrame(dict(name=[\"Austin\", \"NYC\"], lon=[-97.7431,-74.0059], lat=[30.2672,40.7128]))\n", "wgs84_to_web_mercator(df)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "\n", "
\n" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/javascript": [ "(function(root) {\n", " function embed_document(root) {\n", " \n", " var docs_json = {\"049a9c4c-9990-4efa-8251-cdfe32b7509d\":{\"roots\":{\"references\":[{\"attributes\":{\"below\":[{\"id\":\"1170\"}],\"center\":[{\"id\":\"1177\"},{\"id\":\"1185\"}],\"left\":[{\"id\":\"1178\"}],\"renderers\":[{\"id\":\"1192\"},{\"id\":\"1197\"}],\"title\":{\"id\":\"1210\"},\"toolbar\":{\"id\":\"1188\"},\"x_range\":{\"id\":\"1162\"},\"x_scale\":{\"id\":\"1166\"},\"y_range\":{\"id\":\"1164\"},\"y_scale\":{\"id\":\"1168\"}},\"id\":\"1161\",\"subtype\":\"Figure\",\"type\":\"Plot\"},{\"attributes\":{},\"id\":\"1217\",\"type\":\"UnionRenderers\"},{\"attributes\":{\"axis\":{\"id\":\"1178\"},\"dimension\":1,\"ticker\":null},\"id\":\"1185\",\"type\":\"Grid\"},{\"attributes\":{\"text\":\"\"},\"id\":\"1210\",\"type\":\"Title\"},{\"attributes\":{\"formatter\":{\"id\":\"1173\"},\"ticker\":{\"id\":\"1171\"}},\"id\":\"1170\",\"type\":\"MercatorAxis\"},{\"attributes\":{},\"id\":\"1166\",\"type\":\"LinearScale\"},{\"attributes\":{\"attribution\":\"Tiles by Carto, under CC BY 3.0. Data by OSM, under ODbL\",\"url\":\"http://a.basemaps.cartocdn.com/rastertiles/voyager/{Z}/{X}/{Y}.png\"},\"id\":\"1191\",\"type\":\"WMTSTileSource\"},{\"attributes\":{\"data_source\":{\"id\":\"1194\"},\"glyph\":{\"id\":\"1195\"},\"hover_glyph\":null,\"muted_glyph\":null,\"nonselection_glyph\":{\"id\":\"1196\"},\"selection_glyph\":null,\"view\":{\"id\":\"1198\"}},\"id\":\"1197\",\"type\":\"GlyphRenderer\"},{\"attributes\":{\"end\":-7453304,\"start\":-13884029},\"id\":\"1162\",\"type\":\"Range1d\"},{\"attributes\":{\"dimension\":\"lat\"},\"id\":\"1179\",\"type\":\"MercatorTicker\"},{\"attributes\":{\"dimension\":\"lon\"},\"id\":\"1173\",\"type\":\"MercatorTickFormatter\"},{\"attributes\":{\"fill_color\":{\"value\":\"orange\"},\"line_color\":{\"value\":\"#1f77b4\"},\"size\":{\"units\":\"screen\",\"value\":10},\"x\":{\"field\":\"x\"},\"y\":{\"field\":\"y\"}},\"id\":\"1195\",\"type\":\"Circle\"},{\"attributes\":{\"dimension\":\"lon\"},\"id\":\"1171\",\"type\":\"MercatorTicker\"},{\"attributes\":{\"fill_alpha\":{\"value\":0.1},\"fill_color\":{\"value\":\"orange\"},\"line_alpha\":{\"value\":0.1},\"line_color\":{\"value\":\"#1f77b4\"},\"size\":{\"units\":\"screen\",\"value\":10},\"x\":{\"field\":\"x\"},\"y\":{\"field\":\"y\"}},\"id\":\"1196\",\"type\":\"Circle\"},{\"attributes\":{\"active_drag\":\"auto\",\"active_inspect\":\"auto\",\"active_multi\":null,\"active_scroll\":\"auto\",\"active_tap\":\"auto\",\"tools\":[{\"id\":\"1186\"},{\"id\":\"1187\"}]},\"id\":\"1188\",\"type\":\"Toolbar\"},{\"attributes\":{\"data\":{\"x\":{\"__ndarray__\":\"TJjbA9nAZMGf/KLGNm1fwQ==\",\"dtype\":\"float64\",\"shape\":[2]},\"y\":{\"__ndarray__\":\"a6XdLQv+SkFnqxDllfVSQQ==\",\"dtype\":\"float64\",\"shape\":[2]}},\"selected\":{\"id\":\"1216\"},\"selection_policy\":{\"id\":\"1217\"}},\"id\":\"1194\",\"type\":\"ColumnDataSource\"},{\"attributes\":{\"axis\":{\"id\":\"1170\"},\"ticker\":null},\"id\":\"1177\",\"type\":\"Grid\"},{\"attributes\":{},\"id\":\"1168\",\"type\":\"LinearScale\"},{\"attributes\":{},\"id\":\"1187\",\"type\":\"WheelZoomTool\"},{\"attributes\":{},\"id\":\"1186\",\"type\":\"PanTool\"},{\"attributes\":{\"end\":6455972,\"start\":2698291},\"id\":\"1164\",\"type\":\"Range1d\"},{\"attributes\":{\"formatter\":{\"id\":\"1181\"},\"ticker\":{\"id\":\"1179\"}},\"id\":\"1178\",\"type\":\"MercatorAxis\"},{\"attributes\":{\"dimension\":\"lat\"},\"id\":\"1181\",\"type\":\"MercatorTickFormatter\"},{\"attributes\":{\"tile_source\":{\"id\":\"1191\"}},\"id\":\"1192\",\"type\":\"TileRenderer\"},{\"attributes\":{},\"id\":\"1216\",\"type\":\"Selection\"},{\"attributes\":{\"source\":{\"id\":\"1194\"}},\"id\":\"1198\",\"type\":\"CDSView\"}],\"root_ids\":[\"1161\"]},\"title\":\"Bokeh Application\",\"version\":\"2.0.1\"}};\n", " var render_items = [{\"docid\":\"049a9c4c-9990-4efa-8251-cdfe32b7509d\",\"root_ids\":[\"1161\"],\"roots\":{\"1161\":\"f1e96d90-01cf-43aa-9116-3940edff99ef\"}}];\n", " root.Bokeh.embed.embed_items_notebook(docs_json, render_items);\n", "\n", " }\n", " if (root.Bokeh !== undefined) {\n", " embed_document(root);\n", " } else {\n", " var attempts = 0;\n", " var timer = setInterval(function(root) {\n", " if (root.Bokeh !== undefined) {\n", " clearInterval(timer);\n", " embed_document(root);\n", " } else {\n", " attempts++;\n", " if (attempts > 100) {\n", " clearInterval(timer);\n", " console.log(\"Bokeh: ERROR: Unable to run BokehJS code because BokehJS library is missing\");\n", " }\n", " }\n", " }, 10, root)\n", " }\n", "})(window);" ], "application/vnd.bokehjs_exec.v0+json": "" }, "metadata": { "application/vnd.bokehjs_exec.v0+json": { "id": "1161" } }, "output_type": "display_data" } ], "source": [ "p = figure(tools='pan, wheel_zoom', x_range=x_range, y_range=y_range, \n", " x_axis_type=\"mercator\", y_axis_type=\"mercator\")\n", "\n", "p.add_tile(WMTSTileSource(url=url, attribution=attribution))\n", "\n", "p.circle(x=df['x'], y=df['y'], fill_color='orange', size=10)\n", "show(p)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "# EXERCISE: find some data in lat, lon (e.g. at http://data.gov), \n", "# import it into a dataframe or data source, and add it on the map above.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Next Section" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Click on this link to go to the next notebook: [10 - Exporting and Embedding](10%20-%20Exporting%20and%20Embedding.ipynb).\n", "\n", "To go back to the overview, click [here](00%20-%20Introduction%20and%20Setup.ipynb)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.2" } }, "nbformat": 4, "nbformat_minor": 4 }