{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Exploring Recent Shootings in Philadelphia with Altair, Folium, and Panel\n", "\n", "In this notebook, we create an example dashboard visualizing recent shootings in Philadelphia. The dashboard includes:\n", "\n", "- a Folium heatmap of the shootings from the past *X* days, where *X* is specified by the user\n", "- an Altair histogram of victim ages\n", "- an hvplot bar chart showing the number of shootings per day\n", "- a slider for selecting the number of days to query shootings for\n", "\n", "#### References\n", "​\n", "For more information, see the documentation:\n", "​\n", "- [Documentation homepage](https://panel.holoviz.org)\n", "- [App Gallery](https://panel.holoviz.org/gallery/index.html)\n", " - Examples of end-to-end web apps using Panel\n", "- [Component Gallery](https://panel.holoviz.org/reference/index.html)\n", " - Examples (code snippets) for the types of panes, widgets, and layouts possible in Panel dashboards\n", "- [Folium documentation](https://python-visualization.github.io/folium/)\n", "\n", "\n", "For this dashboard, check out the following reference examples:\n", "\n", "1. See the **Altair/Vega** [reference gallery page](https://panel.holoviz.org/reference/panes/Vega.html) for more information about embedding Altair in Panel dashboards.\n", "\n", "2. See the **Folium** [reference gallery page](https://panel.holoviz.org/reference/panes/Folium.html) for more information about embedding Folium in Panel dashboards." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/javascript": [ "(function(root) {\n", " function now() {\n", " return new Date();\n", " }\n", "\n", " const force = true;\n", " const py_version = '3.5.2'.replace('rc', '-rc.').replace('.dev', '-dev.');\n", " const reloading = false;\n", " const Bokeh = root.Bokeh;\n", "\n", " // Set a timeout for this load but only if we are not already initializing\n", " if (typeof (root._bokeh_timeout) === \"undefined\" || (force || !root._bokeh_is_initializing)) {\n", " root._bokeh_timeout = Date.now() + 5000;\n", " root._bokeh_failed_load = false;\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, js_modules, js_exports, callback) {\n", " if (css_urls == null) css_urls = [];\n", " if (js_urls == null) js_urls = [];\n", " if (js_modules == null) js_modules = [];\n", " if (js_exports == null) js_exports = {};\n", "\n", " root._bokeh_onload_callbacks.push(callback);\n", "\n", " if (root._bokeh_is_loading > 0) {\n", " // Don't load bokeh if it is still initializing\n", " console.debug(\"Bokeh: BokehJS is being loaded, scheduling callback at\", now());\n", " return null;\n", " } else if (js_urls.length === 0 && js_modules.length === 0 && Object.keys(js_exports).length === 0) {\n", " // There is nothing to load\n", " run_callbacks();\n", " return null;\n", " }\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", " window._bokeh_on_load = on_load\n", "\n", " function on_error(e) {\n", " const src_el = e.srcElement\n", " console.error(\"failed to load \" + (src_el.href || src_el.src));\n", " }\n", "\n", " const skip = [];\n", " if (window.requirejs) {\n", " window.requirejs.config({'packages': {}, 'paths': {'vega-embed': 'https://cdn.jsdelivr.net/npm/vega-embed@6/build/vega-embed.min', 'vega-lite': 'https://cdn.jsdelivr.net/npm/vega-lite@5/build/vega-lite.min', 'vega': 'https://cdn.jsdelivr.net/npm/vega@5/build/vega.min'}, 'shim': {}});\n", " require([\"vega-embed\"], function(vegaEmbed) {\n", " window.vegaEmbed = vegaEmbed\n", " on_load()\n", " })\n", " require([\"vega-lite\"], function(vl) {\n", " window.vl = vl\n", " on_load()\n", " })\n", " require([\"vega\"], function(vega) {\n", " window.vega = vega\n", " on_load()\n", " })\n", " root._bokeh_is_loading = css_urls.length + 3;\n", " } else {\n", " root._bokeh_is_loading = css_urls.length + js_urls.length + js_modules.length + Object.keys(js_exports).length;\n", " }\n", "\n", " const existing_stylesheets = []\n", " const links = document.getElementsByTagName('link')\n", " for (let i = 0; i < links.length; i++) {\n", " const link = links[i]\n", " if (link.href != null) {\n", " existing_stylesheets.push(link.href)\n", " }\n", " }\n", " for (let i = 0; i < css_urls.length; i++) {\n", " const url = css_urls[i];\n", " const escaped = encodeURI(url)\n", " if (existing_stylesheets.indexOf(escaped) !== -1) {\n", " on_load()\n", " continue;\n", " }\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", " } if (((window.vega !== undefined) && (!(window.vega instanceof HTMLElement))) || window.requirejs) {\n", " var urls = ['https://cdn.holoviz.org/panel/1.5.4/dist/bundled/vegaplot/vega@5'];\n", " for (var i = 0; i < urls.length; i++) {\n", " skip.push(encodeURI(urls[i]))\n", " }\n", " } if (((window.vegaLite !== undefined) && (!(window.vegaLite instanceof HTMLElement))) || window.requirejs) {\n", " var urls = ['https://cdn.holoviz.org/panel/1.5.4/dist/bundled/vegaplot/vega-lite@5'];\n", " for (var i = 0; i < urls.length; i++) {\n", " skip.push(encodeURI(urls[i]))\n", " }\n", " } if (((window.vegaEmbed !== undefined) && (!(window.vegaEmbed instanceof HTMLElement))) || window.requirejs) {\n", " var urls = ['https://cdn.holoviz.org/panel/1.5.4/dist/bundled/vegaplot/vega-embed@6'];\n", " for (var i = 0; i < urls.length; i++) {\n", " skip.push(encodeURI(urls[i]))\n", " }\n", " } var existing_scripts = []\n", " const scripts = document.getElementsByTagName('script')\n", " for (let i = 0; i < scripts.length; i++) {\n", " var script = scripts[i]\n", " if (script.src != null) {\n", " existing_scripts.push(script.src)\n", " }\n", " }\n", " for (let i = 0; i < js_urls.length; i++) {\n", " const url = js_urls[i];\n", " const escaped = encodeURI(url)\n", " if (skip.indexOf(escaped) !== -1 || existing_scripts.indexOf(escaped) !== -1) {\n", " if (!window.requirejs) {\n", " on_load();\n", " }\n", " continue;\n", " }\n", " const element = document.createElement('script');\n", " element.onload = on_load;\n", " element.onerror = on_error;\n", " element.async = false;\n", " element.src = url;\n", " console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n", " document.head.appendChild(element);\n", " }\n", " for (let i = 0; i < js_modules.length; i++) {\n", " const url = js_modules[i];\n", " const escaped = encodeURI(url)\n", " if (skip.indexOf(escaped) !== -1 || existing_scripts.indexOf(escaped) !== -1) {\n", " if (!window.requirejs) {\n", " on_load();\n", " }\n", " continue;\n", " }\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", " element.type = \"module\";\n", " console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n", " document.head.appendChild(element);\n", " }\n", " for (const name in js_exports) {\n", " const url = js_exports[name];\n", " const escaped = encodeURI(url)\n", " if (skip.indexOf(escaped) >= 0 || root[name] != null) {\n", " if (!window.requirejs) {\n", " on_load();\n", " }\n", " continue;\n", " }\n", " var element = document.createElement('script');\n", " element.onerror = on_error;\n", " element.async = false;\n", " element.type = \"module\";\n", " console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n", " element.textContent = `\n", " import ${name} from \"${url}\"\n", " window.${name} = ${name}\n", " window._bokeh_on_load()\n", " `\n", " document.head.appendChild(element);\n", " }\n", " if (!js_urls.length && !js_modules.length) {\n", " on_load()\n", " }\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", " const js_urls = [\"https://cdn.holoviz.org/panel/1.5.4/dist/bundled/reactiveesm/es-module-shims@^1.10.0/dist/es-module-shims.min.js\", \"https://cdn.holoviz.org/panel/1.5.4/dist/bundled/vegaplot/vega@5\", \"https://cdn.holoviz.org/panel/1.5.4/dist/bundled/vegaplot/vega-lite@5\", \"https://cdn.holoviz.org/panel/1.5.4/dist/bundled/vegaplot/vega-embed@6\", \"https://cdn.bokeh.org/bokeh/release/bokeh-3.5.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-gl-3.5.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-3.5.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-3.5.2.min.js\", \"https://cdn.holoviz.org/panel/1.5.4/dist/panel.min.js\"];\n", " const js_modules = [];\n", " const js_exports = {};\n", " const css_urls = [];\n", " const inline_js = [ function(Bokeh) {\n", " Bokeh.set_log_level(\"info\");\n", " },\n", "function(Bokeh) {} // ensure no trailing comma for IE\n", " ];\n", "\n", " function run_inline_js() {\n", " if ((root.Bokeh !== undefined) || (force === true)) {\n", " for (let i = 0; i < inline_js.length; i++) {\n", " try {\n", " inline_js[i].call(root, root.Bokeh);\n", " } catch(e) {\n", " if (!reloading) {\n", " throw e;\n", " }\n", " }\n", " }\n", " // Cache old bokeh versions\n", " if (Bokeh != undefined && !reloading) {\n", " var NewBokeh = root.Bokeh;\n", " if (Bokeh.versions === undefined) {\n", " Bokeh.versions = new Map();\n", " }\n", " if (NewBokeh.version !== Bokeh.version) {\n", " Bokeh.versions.set(NewBokeh.version, NewBokeh)\n", " }\n", " root.Bokeh = Bokeh;\n", " }\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", " }\n", " root._bokeh_is_initializing = false\n", " }\n", "\n", " function load_or_wait() {\n", " // Implement a backoff loop that tries to ensure we do not load multiple\n", " // versions of Bokeh and its dependencies at the same time.\n", " // In recent versions we use the root._bokeh_is_initializing flag\n", " // to determine whether there is an ongoing attempt to initialize\n", " // bokeh, however for backward compatibility we also try to ensure\n", " // that we do not start loading a newer (Panel>=1.0 and Bokeh>3) version\n", " // before older versions are fully initialized.\n", " if (root._bokeh_is_initializing && Date.now() > root._bokeh_timeout) {\n", " // If the timeout and bokeh was not successfully loaded we reset\n", " // everything and try loading again\n", " root._bokeh_timeout = Date.now() + 5000;\n", " root._bokeh_is_initializing = false;\n", " root._bokeh_onload_callbacks = undefined;\n", " root._bokeh_is_loading = 0\n", " console.log(\"Bokeh: BokehJS was loaded multiple times but one version failed to initialize.\");\n", " load_or_wait();\n", " } else if (root._bokeh_is_initializing || (typeof root._bokeh_is_initializing === \"undefined\" && root._bokeh_onload_callbacks !== undefined)) {\n", " setTimeout(load_or_wait, 100);\n", " } else {\n", " root._bokeh_is_initializing = true\n", " root._bokeh_onload_callbacks = []\n", " const bokeh_loaded = root.Bokeh != null && (root.Bokeh.version === py_version || (root.Bokeh.versions !== undefined && root.Bokeh.versions.has(py_version)));\n", " if (!reloading && !bokeh_loaded) {\n", " if (root.Bokeh) {\n", " root.Bokeh = undefined;\n", " }\n", " console.debug(\"Bokeh: BokehJS not loaded, scheduling load and callback at\", now());\n", " }\n", " load_libs(css_urls, js_urls, js_modules, js_exports, function() {\n", " console.debug(\"Bokeh: BokehJS plotting callback run at\", now());\n", " run_inline_js();\n", " });\n", " }\n", " }\n", " // Give older versions of the autoload script a head-start to ensure\n", " // they initialize before we start loading newer version.\n", " setTimeout(load_or_wait, 100)\n", "}(window));" ], "application/vnd.holoviews_load.v0+json": "(function(root) {\n function now() {\n return new Date();\n }\n\n const force = true;\n const py_version = '3.5.2'.replace('rc', '-rc.').replace('.dev', '-dev.');\n const reloading = false;\n const Bokeh = root.Bokeh;\n\n // Set a timeout for this load but only if we are not already initializing\n if (typeof (root._bokeh_timeout) === \"undefined\" || (force || !root._bokeh_is_initializing)) {\n root._bokeh_timeout = Date.now() + 5000;\n root._bokeh_failed_load = false;\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, js_modules, js_exports, callback) {\n if (css_urls == null) css_urls = [];\n if (js_urls == null) js_urls = [];\n if (js_modules == null) js_modules = [];\n if (js_exports == null) js_exports = {};\n\n root._bokeh_onload_callbacks.push(callback);\n\n if (root._bokeh_is_loading > 0) {\n // Don't load bokeh if it is still initializing\n console.debug(\"Bokeh: BokehJS is being loaded, scheduling callback at\", now());\n return null;\n } else if (js_urls.length === 0 && js_modules.length === 0 && Object.keys(js_exports).length === 0) {\n // There is nothing to load\n run_callbacks();\n return null;\n }\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 window._bokeh_on_load = on_load\n\n function on_error(e) {\n const src_el = e.srcElement\n console.error(\"failed to load \" + (src_el.href || src_el.src));\n }\n\n const skip = [];\n if (window.requirejs) {\n window.requirejs.config({'packages': {}, 'paths': {'vega-embed': 'https://cdn.jsdelivr.net/npm/vega-embed@6/build/vega-embed.min', 'vega-lite': 'https://cdn.jsdelivr.net/npm/vega-lite@5/build/vega-lite.min', 'vega': 'https://cdn.jsdelivr.net/npm/vega@5/build/vega.min'}, 'shim': {}});\n require([\"vega-embed\"], function(vegaEmbed) {\n window.vegaEmbed = vegaEmbed\n on_load()\n })\n require([\"vega-lite\"], function(vl) {\n window.vl = vl\n on_load()\n })\n require([\"vega\"], function(vega) {\n window.vega = vega\n on_load()\n })\n root._bokeh_is_loading = css_urls.length + 3;\n } else {\n root._bokeh_is_loading = css_urls.length + js_urls.length + js_modules.length + Object.keys(js_exports).length;\n }\n\n const existing_stylesheets = []\n const links = document.getElementsByTagName('link')\n for (let i = 0; i < links.length; i++) {\n const link = links[i]\n if (link.href != null) {\n existing_stylesheets.push(link.href)\n }\n }\n for (let i = 0; i < css_urls.length; i++) {\n const url = css_urls[i];\n const escaped = encodeURI(url)\n if (existing_stylesheets.indexOf(escaped) !== -1) {\n on_load()\n continue;\n }\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 } if (((window.vega !== undefined) && (!(window.vega instanceof HTMLElement))) || window.requirejs) {\n var urls = ['https://cdn.holoviz.org/panel/1.5.4/dist/bundled/vegaplot/vega@5'];\n for (var i = 0; i < urls.length; i++) {\n skip.push(encodeURI(urls[i]))\n }\n } if (((window.vegaLite !== undefined) && (!(window.vegaLite instanceof HTMLElement))) || window.requirejs) {\n var urls = ['https://cdn.holoviz.org/panel/1.5.4/dist/bundled/vegaplot/vega-lite@5'];\n for (var i = 0; i < urls.length; i++) {\n skip.push(encodeURI(urls[i]))\n }\n } if (((window.vegaEmbed !== undefined) && (!(window.vegaEmbed instanceof HTMLElement))) || window.requirejs) {\n var urls = ['https://cdn.holoviz.org/panel/1.5.4/dist/bundled/vegaplot/vega-embed@6'];\n for (var i = 0; i < urls.length; i++) {\n skip.push(encodeURI(urls[i]))\n }\n } var existing_scripts = []\n const scripts = document.getElementsByTagName('script')\n for (let i = 0; i < scripts.length; i++) {\n var script = scripts[i]\n if (script.src != null) {\n existing_scripts.push(script.src)\n }\n }\n for (let i = 0; i < js_urls.length; i++) {\n const url = js_urls[i];\n const escaped = encodeURI(url)\n if (skip.indexOf(escaped) !== -1 || existing_scripts.indexOf(escaped) !== -1) {\n if (!window.requirejs) {\n on_load();\n }\n continue;\n }\n const element = document.createElement('script');\n element.onload = on_load;\n element.onerror = on_error;\n element.async = false;\n element.src = url;\n console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n document.head.appendChild(element);\n }\n for (let i = 0; i < js_modules.length; i++) {\n const url = js_modules[i];\n const escaped = encodeURI(url)\n if (skip.indexOf(escaped) !== -1 || existing_scripts.indexOf(escaped) !== -1) {\n if (!window.requirejs) {\n on_load();\n }\n continue;\n }\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 element.type = \"module\";\n console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n document.head.appendChild(element);\n }\n for (const name in js_exports) {\n const url = js_exports[name];\n const escaped = encodeURI(url)\n if (skip.indexOf(escaped) >= 0 || root[name] != null) {\n if (!window.requirejs) {\n on_load();\n }\n continue;\n }\n var element = document.createElement('script');\n element.onerror = on_error;\n element.async = false;\n element.type = \"module\";\n console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n element.textContent = `\n import ${name} from \"${url}\"\n window.${name} = ${name}\n window._bokeh_on_load()\n `\n document.head.appendChild(element);\n }\n if (!js_urls.length && !js_modules.length) {\n on_load()\n }\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 const js_urls = [\"https://cdn.holoviz.org/panel/1.5.4/dist/bundled/reactiveesm/es-module-shims@^1.10.0/dist/es-module-shims.min.js\", \"https://cdn.holoviz.org/panel/1.5.4/dist/bundled/vegaplot/vega@5\", \"https://cdn.holoviz.org/panel/1.5.4/dist/bundled/vegaplot/vega-lite@5\", \"https://cdn.holoviz.org/panel/1.5.4/dist/bundled/vegaplot/vega-embed@6\", \"https://cdn.bokeh.org/bokeh/release/bokeh-3.5.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-gl-3.5.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-3.5.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-3.5.2.min.js\", \"https://cdn.holoviz.org/panel/1.5.4/dist/panel.min.js\"];\n const js_modules = [];\n const js_exports = {};\n const css_urls = [];\n const inline_js = [ function(Bokeh) {\n Bokeh.set_log_level(\"info\");\n },\nfunction(Bokeh) {} // ensure no trailing comma for IE\n ];\n\n function run_inline_js() {\n if ((root.Bokeh !== undefined) || (force === true)) {\n for (let i = 0; i < inline_js.length; i++) {\n try {\n inline_js[i].call(root, root.Bokeh);\n } catch(e) {\n if (!reloading) {\n throw e;\n }\n }\n }\n // Cache old bokeh versions\n if (Bokeh != undefined && !reloading) {\n var NewBokeh = root.Bokeh;\n if (Bokeh.versions === undefined) {\n Bokeh.versions = new Map();\n }\n if (NewBokeh.version !== Bokeh.version) {\n Bokeh.versions.set(NewBokeh.version, NewBokeh)\n }\n root.Bokeh = Bokeh;\n }\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 }\n root._bokeh_is_initializing = false\n }\n\n function load_or_wait() {\n // Implement a backoff loop that tries to ensure we do not load multiple\n // versions of Bokeh and its dependencies at the same time.\n // In recent versions we use the root._bokeh_is_initializing flag\n // to determine whether there is an ongoing attempt to initialize\n // bokeh, however for backward compatibility we also try to ensure\n // that we do not start loading a newer (Panel>=1.0 and Bokeh>3) version\n // before older versions are fully initialized.\n if (root._bokeh_is_initializing && Date.now() > root._bokeh_timeout) {\n // If the timeout and bokeh was not successfully loaded we reset\n // everything and try loading again\n root._bokeh_timeout = Date.now() + 5000;\n root._bokeh_is_initializing = false;\n root._bokeh_onload_callbacks = undefined;\n root._bokeh_is_loading = 0\n console.log(\"Bokeh: BokehJS was loaded multiple times but one version failed to initialize.\");\n load_or_wait();\n } else if (root._bokeh_is_initializing || (typeof root._bokeh_is_initializing === \"undefined\" && root._bokeh_onload_callbacks !== undefined)) {\n setTimeout(load_or_wait, 100);\n } else {\n root._bokeh_is_initializing = true\n root._bokeh_onload_callbacks = []\n const bokeh_loaded = root.Bokeh != null && (root.Bokeh.version === py_version || (root.Bokeh.versions !== undefined && root.Bokeh.versions.has(py_version)));\n if (!reloading && !bokeh_loaded) {\n if (root.Bokeh) {\n root.Bokeh = undefined;\n }\n console.debug(\"Bokeh: BokehJS not loaded, scheduling load and callback at\", now());\n }\n load_libs(css_urls, js_urls, js_modules, js_exports, function() {\n console.debug(\"Bokeh: BokehJS plotting callback run at\", now());\n run_inline_js();\n });\n }\n }\n // Give older versions of the autoload script a head-start to ensure\n // they initialize before we start loading newer version.\n setTimeout(load_or_wait, 100)\n}(window));" }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/javascript": [ "\n", "if ((window.PyViz === undefined) || (window.PyViz instanceof HTMLElement)) {\n", " window.PyViz = {comms: {}, comm_status:{}, kernels:{}, receivers: {}, plot_index: []}\n", "}\n", "\n", "\n", " function JupyterCommManager() {\n", " }\n", "\n", " JupyterCommManager.prototype.register_target = function(plot_id, comm_id, msg_handler) {\n", " if (window.comm_manager || ((window.Jupyter !== undefined) && (Jupyter.notebook.kernel != null))) {\n", " var comm_manager = window.comm_manager || Jupyter.notebook.kernel.comm_manager;\n", " comm_manager.register_target(comm_id, function(comm) {\n", " comm.on_msg(msg_handler);\n", " });\n", " } else if ((plot_id in window.PyViz.kernels) && (window.PyViz.kernels[plot_id])) {\n", " window.PyViz.kernels[plot_id].registerCommTarget(comm_id, function(comm) {\n", " comm.onMsg = msg_handler;\n", " });\n", " } else if (typeof google != 'undefined' && google.colab.kernel != null) {\n", " google.colab.kernel.comms.registerTarget(comm_id, (comm) => {\n", " var messages = comm.messages[Symbol.asyncIterator]();\n", " function processIteratorResult(result) {\n", " var message = result.value;\n", " console.log(message)\n", " var content = {data: message.data, comm_id};\n", " var buffers = []\n", " for (var buffer of message.buffers || []) {\n", " buffers.push(new DataView(buffer))\n", " }\n", " var metadata = message.metadata || {};\n", " var msg = {content, buffers, metadata}\n", " msg_handler(msg);\n", " return messages.next().then(processIteratorResult);\n", " }\n", " return messages.next().then(processIteratorResult);\n", " })\n", " }\n", " }\n", "\n", " JupyterCommManager.prototype.get_client_comm = function(plot_id, comm_id, msg_handler) {\n", " if (comm_id in window.PyViz.comms) {\n", " return window.PyViz.comms[comm_id];\n", " } else if (window.comm_manager || ((window.Jupyter !== undefined) && (Jupyter.notebook.kernel != null))) {\n", " var comm_manager = window.comm_manager || Jupyter.notebook.kernel.comm_manager;\n", " var comm = comm_manager.new_comm(comm_id, {}, {}, {}, comm_id);\n", " if (msg_handler) {\n", " comm.on_msg(msg_handler);\n", " }\n", " } else if ((plot_id in window.PyViz.kernels) && (window.PyViz.kernels[plot_id])) {\n", " var comm = window.PyViz.kernels[plot_id].connectToComm(comm_id);\n", " comm.open();\n", " if (msg_handler) {\n", " comm.onMsg = msg_handler;\n", " }\n", " } else if (typeof google != 'undefined' && google.colab.kernel != null) {\n", " var comm_promise = google.colab.kernel.comms.open(comm_id)\n", " comm_promise.then((comm) => {\n", " window.PyViz.comms[comm_id] = comm;\n", " if (msg_handler) {\n", " var messages = comm.messages[Symbol.asyncIterator]();\n", " function processIteratorResult(result) {\n", " var message = result.value;\n", " var content = {data: message.data};\n", " var metadata = message.metadata || {comm_id};\n", " var msg = {content, metadata}\n", " msg_handler(msg);\n", " return messages.next().then(processIteratorResult);\n", " }\n", " return messages.next().then(processIteratorResult);\n", " }\n", " }) \n", " var sendClosure = (data, metadata, buffers, disposeOnDone) => {\n", " return comm_promise.then((comm) => {\n", " comm.send(data, metadata, buffers, disposeOnDone);\n", " });\n", " };\n", " var comm = {\n", " send: sendClosure\n", " };\n", " }\n", " window.PyViz.comms[comm_id] = comm;\n", " return comm;\n", " }\n", " window.PyViz.comm_manager = new JupyterCommManager();\n", " \n", "\n", "\n", "var JS_MIME_TYPE = 'application/javascript';\n", "var HTML_MIME_TYPE = 'text/html';\n", "var EXEC_MIME_TYPE = 'application/vnd.holoviews_exec.v0+json';\n", "var CLASS_NAME = 'output';\n", "\n", "/**\n", " * Render data to the DOM node\n", " */\n", "function render(props, node) {\n", " var div = document.createElement(\"div\");\n", " var script = document.createElement(\"script\");\n", " node.appendChild(div);\n", " node.appendChild(script);\n", "}\n", "\n", "/**\n", " * Handle when a new output is added\n", " */\n", "function handle_add_output(event, handle) {\n", " var output_area = handle.output_area;\n", " var output = handle.output;\n", " if ((output.data == undefined) || (!output.data.hasOwnProperty(EXEC_MIME_TYPE))) {\n", " return\n", " }\n", " var id = output.metadata[EXEC_MIME_TYPE][\"id\"];\n", " var toinsert = output_area.element.find(\".\" + CLASS_NAME.split(' ')[0]);\n", " if (id !== undefined) {\n", " var nchildren = toinsert.length;\n", " var html_node = toinsert[nchildren-1].children[0];\n", " html_node.innerHTML = output.data[HTML_MIME_TYPE];\n", " var scripts = [];\n", " var nodelist = html_node.querySelectorAll(\"script\");\n", " for (var i in nodelist) {\n", " if (nodelist.hasOwnProperty(i)) {\n", " scripts.push(nodelist[i])\n", " }\n", " }\n", "\n", " scripts.forEach( function (oldScript) {\n", " var newScript = document.createElement(\"script\");\n", " var attrs = [];\n", " var nodemap = oldScript.attributes;\n", " for (var j in nodemap) {\n", " if (nodemap.hasOwnProperty(j)) {\n", " attrs.push(nodemap[j])\n", " }\n", " }\n", " attrs.forEach(function(attr) { newScript.setAttribute(attr.name, attr.value) });\n", " newScript.appendChild(document.createTextNode(oldScript.innerHTML));\n", " oldScript.parentNode.replaceChild(newScript, oldScript);\n", " });\n", " if (JS_MIME_TYPE in output.data) {\n", " toinsert[nchildren-1].children[1].textContent = output.data[JS_MIME_TYPE];\n", " }\n", " output_area._hv_plot_id = id;\n", " if ((window.Bokeh !== undefined) && (id in Bokeh.index)) {\n", " window.PyViz.plot_index[id] = Bokeh.index[id];\n", " } else {\n", " window.PyViz.plot_index[id] = null;\n", " }\n", " } else 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].childNodes[1].setAttribute(script_attrs[i].name, script_attrs[i].value);\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", "/**\n", " * Handle when an output is cleared or removed\n", " */\n", "function handle_clear_output(event, handle) {\n", " var id = handle.cell.output_area._hv_plot_id;\n", " var server_id = handle.cell.output_area._bokeh_server_id;\n", " if (((id === undefined) || !(id in PyViz.plot_index)) && (server_id !== undefined)) { return; }\n", " var comm = window.PyViz.comm_manager.get_client_comm(\"hv-extension-comm\", \"hv-extension-comm\", function () {});\n", " if (server_id !== null) {\n", " comm.send({event_type: 'server_delete', 'id': server_id});\n", " return;\n", " } else if (comm !== null) {\n", " comm.send({event_type: 'delete', 'id': id});\n", " }\n", " delete PyViz.plot_index[id];\n", " if ((window.Bokeh !== undefined) & (id in window.Bokeh.index)) {\n", " var doc = window.Bokeh.index[id].model.document\n", " doc.clear();\n", " const i = window.Bokeh.documents.indexOf(doc);\n", " if (i > -1) {\n", " window.Bokeh.documents.splice(i, 1);\n", " }\n", " }\n", "}\n", "\n", "/**\n", " * Handle kernel restart event\n", " */\n", "function handle_kernel_cleanup(event, handle) {\n", " delete PyViz.comms[\"hv-extension-comm\"];\n", " window.PyViz.plot_index = {}\n", "}\n", "\n", "/**\n", " * Handle update_display_data messages\n", " */\n", "function handle_update_output(event, handle) {\n", " handle_clear_output(event, {cell: {output_area: handle.output_area}})\n", " handle_add_output(event, handle)\n", "}\n", "\n", "function register_renderer(events, OutputArea) {\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[0]);\n", " element.append(toinsert);\n", " return toinsert\n", " }\n", "\n", " events.on('output_added.OutputArea', handle_add_output);\n", " events.on('output_updated.OutputArea', handle_update_output);\n", " events.on('clear_output.CodeCell', handle_clear_output);\n", " events.on('delete.Cell', handle_clear_output);\n", " events.on('kernel_ready.Kernel', handle_kernel_cleanup);\n", "\n", " OutputArea.prototype.register_mime_type(EXEC_MIME_TYPE, append_mime, {\n", " safe: true,\n", " index: 0\n", " });\n", "}\n", "\n", "if (window.Jupyter !== undefined) {\n", " try {\n", " var events = require('base/js/events');\n", " var OutputArea = require('notebook/js/outputarea').OutputArea;\n", " if (OutputArea.prototype.mime_types().indexOf(EXEC_MIME_TYPE) == -1) {\n", " register_renderer(events, OutputArea);\n", " }\n", " } catch(err) {\n", " }\n", "}\n" ], "application/vnd.holoviews_load.v0+json": "\nif ((window.PyViz === undefined) || (window.PyViz instanceof HTMLElement)) {\n window.PyViz = {comms: {}, comm_status:{}, kernels:{}, receivers: {}, plot_index: []}\n}\n\n\n function JupyterCommManager() {\n }\n\n JupyterCommManager.prototype.register_target = function(plot_id, comm_id, msg_handler) {\n if (window.comm_manager || ((window.Jupyter !== undefined) && (Jupyter.notebook.kernel != null))) {\n var comm_manager = window.comm_manager || Jupyter.notebook.kernel.comm_manager;\n comm_manager.register_target(comm_id, function(comm) {\n comm.on_msg(msg_handler);\n });\n } else if ((plot_id in window.PyViz.kernels) && (window.PyViz.kernels[plot_id])) {\n window.PyViz.kernels[plot_id].registerCommTarget(comm_id, function(comm) {\n comm.onMsg = msg_handler;\n });\n } else if (typeof google != 'undefined' && google.colab.kernel != null) {\n google.colab.kernel.comms.registerTarget(comm_id, (comm) => {\n var messages = comm.messages[Symbol.asyncIterator]();\n function processIteratorResult(result) {\n var message = result.value;\n console.log(message)\n var content = {data: message.data, comm_id};\n var buffers = []\n for (var buffer of message.buffers || []) {\n buffers.push(new DataView(buffer))\n }\n var metadata = message.metadata || {};\n var msg = {content, buffers, metadata}\n msg_handler(msg);\n return messages.next().then(processIteratorResult);\n }\n return messages.next().then(processIteratorResult);\n })\n }\n }\n\n JupyterCommManager.prototype.get_client_comm = function(plot_id, comm_id, msg_handler) {\n if (comm_id in window.PyViz.comms) {\n return window.PyViz.comms[comm_id];\n } else if (window.comm_manager || ((window.Jupyter !== undefined) && (Jupyter.notebook.kernel != null))) {\n var comm_manager = window.comm_manager || Jupyter.notebook.kernel.comm_manager;\n var comm = comm_manager.new_comm(comm_id, {}, {}, {}, comm_id);\n if (msg_handler) {\n comm.on_msg(msg_handler);\n }\n } else if ((plot_id in window.PyViz.kernels) && (window.PyViz.kernels[plot_id])) {\n var comm = window.PyViz.kernels[plot_id].connectToComm(comm_id);\n comm.open();\n if (msg_handler) {\n comm.onMsg = msg_handler;\n }\n } else if (typeof google != 'undefined' && google.colab.kernel != null) {\n var comm_promise = google.colab.kernel.comms.open(comm_id)\n comm_promise.then((comm) => {\n window.PyViz.comms[comm_id] = comm;\n if (msg_handler) {\n var messages = comm.messages[Symbol.asyncIterator]();\n function processIteratorResult(result) {\n var message = result.value;\n var content = {data: message.data};\n var metadata = message.metadata || {comm_id};\n var msg = {content, metadata}\n msg_handler(msg);\n return messages.next().then(processIteratorResult);\n }\n return messages.next().then(processIteratorResult);\n }\n }) \n var sendClosure = (data, metadata, buffers, disposeOnDone) => {\n return comm_promise.then((comm) => {\n comm.send(data, metadata, buffers, disposeOnDone);\n });\n };\n var comm = {\n send: sendClosure\n };\n }\n window.PyViz.comms[comm_id] = comm;\n return comm;\n }\n window.PyViz.comm_manager = new JupyterCommManager();\n \n\n\nvar JS_MIME_TYPE = 'application/javascript';\nvar HTML_MIME_TYPE = 'text/html';\nvar EXEC_MIME_TYPE = 'application/vnd.holoviews_exec.v0+json';\nvar CLASS_NAME = 'output';\n\n/**\n * Render data to the DOM node\n */\nfunction render(props, node) {\n var div = document.createElement(\"div\");\n var script = document.createElement(\"script\");\n node.appendChild(div);\n node.appendChild(script);\n}\n\n/**\n * Handle when a new output is added\n */\nfunction handle_add_output(event, handle) {\n var output_area = handle.output_area;\n var output = handle.output;\n if ((output.data == undefined) || (!output.data.hasOwnProperty(EXEC_MIME_TYPE))) {\n return\n }\n var id = output.metadata[EXEC_MIME_TYPE][\"id\"];\n var toinsert = output_area.element.find(\".\" + CLASS_NAME.split(' ')[0]);\n if (id !== undefined) {\n var nchildren = toinsert.length;\n var html_node = toinsert[nchildren-1].children[0];\n html_node.innerHTML = output.data[HTML_MIME_TYPE];\n var scripts = [];\n var nodelist = html_node.querySelectorAll(\"script\");\n for (var i in nodelist) {\n if (nodelist.hasOwnProperty(i)) {\n scripts.push(nodelist[i])\n }\n }\n\n scripts.forEach( function (oldScript) {\n var newScript = document.createElement(\"script\");\n var attrs = [];\n var nodemap = oldScript.attributes;\n for (var j in nodemap) {\n if (nodemap.hasOwnProperty(j)) {\n attrs.push(nodemap[j])\n }\n }\n attrs.forEach(function(attr) { newScript.setAttribute(attr.name, attr.value) });\n newScript.appendChild(document.createTextNode(oldScript.innerHTML));\n oldScript.parentNode.replaceChild(newScript, oldScript);\n });\n if (JS_MIME_TYPE in output.data) {\n toinsert[nchildren-1].children[1].textContent = output.data[JS_MIME_TYPE];\n }\n output_area._hv_plot_id = id;\n if ((window.Bokeh !== undefined) && (id in Bokeh.index)) {\n window.PyViz.plot_index[id] = Bokeh.index[id];\n } else {\n window.PyViz.plot_index[id] = null;\n }\n } else 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].childNodes[1].setAttribute(script_attrs[i].name, script_attrs[i].value);\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/**\n * Handle when an output is cleared or removed\n */\nfunction handle_clear_output(event, handle) {\n var id = handle.cell.output_area._hv_plot_id;\n var server_id = handle.cell.output_area._bokeh_server_id;\n if (((id === undefined) || !(id in PyViz.plot_index)) && (server_id !== undefined)) { return; }\n var comm = window.PyViz.comm_manager.get_client_comm(\"hv-extension-comm\", \"hv-extension-comm\", function () {});\n if (server_id !== null) {\n comm.send({event_type: 'server_delete', 'id': server_id});\n return;\n } else if (comm !== null) {\n comm.send({event_type: 'delete', 'id': id});\n }\n delete PyViz.plot_index[id];\n if ((window.Bokeh !== undefined) & (id in window.Bokeh.index)) {\n var doc = window.Bokeh.index[id].model.document\n doc.clear();\n const i = window.Bokeh.documents.indexOf(doc);\n if (i > -1) {\n window.Bokeh.documents.splice(i, 1);\n }\n }\n}\n\n/**\n * Handle kernel restart event\n */\nfunction handle_kernel_cleanup(event, handle) {\n delete PyViz.comms[\"hv-extension-comm\"];\n window.PyViz.plot_index = {}\n}\n\n/**\n * Handle update_display_data messages\n */\nfunction handle_update_output(event, handle) {\n handle_clear_output(event, {cell: {output_area: handle.output_area}})\n handle_add_output(event, handle)\n}\n\nfunction register_renderer(events, OutputArea) {\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[0]);\n element.append(toinsert);\n return toinsert\n }\n\n events.on('output_added.OutputArea', handle_add_output);\n events.on('output_updated.OutputArea', handle_update_output);\n events.on('clear_output.CodeCell', handle_clear_output);\n events.on('delete.Cell', handle_clear_output);\n events.on('kernel_ready.Kernel', handle_kernel_cleanup);\n\n OutputArea.prototype.register_mime_type(EXEC_MIME_TYPE, append_mime, {\n safe: true,\n index: 0\n });\n}\n\nif (window.Jupyter !== undefined) {\n try {\n var events = require('base/js/events');\n var OutputArea = require('notebook/js/outputarea').OutputArea;\n if (OutputArea.prototype.mime_types().indexOf(EXEC_MIME_TYPE) == -1) {\n register_renderer(events, OutputArea);\n }\n } catch(err) {\n }\n}\n" }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.holoviews_exec.v0+json": "", "text/html": [ "
\n", "
\n", "
\n", "" ] }, "metadata": { "application/vnd.holoviews_exec.v0+json": { "id": "7ea313b0-7429-4a7d-9d66-0389bbbc2498" } }, "output_type": "display_data" } ], "source": [ "import panel as pn\n", "\n", "pn.extension(\"vega\") # Enables support for vega/altair" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd\n", "import geopandas as gpd\n", "import requests\n", "\n", "import holoviews as hv\n", "import hvplot.pandas\n", "import param as pm\n", "\n", "import altair as alt\n", "import folium\n", "from folium.plugins import HeatMap" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Load the full data set\n", "\n", "We'll load the full data set before initializing the app, and then the user will be able to filter and display subsets of the entire data set. \n", "\n", "The maximum of our slider will be 365 days, so we only need to query data from the past year. When the user slides the slider, we can select the subset of this full dataset to apply." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "# The maximum number of days into past to query\n", "# NOTE: this will be the maximum number of days the user will be allowed to select\n", "MAX_DAYS = 365\n", "MIN_DAYS = 30" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Query the CARTO API\n", "\n", "Get shooting victim data from Open Data Philly for all data within the last 365 days.\n", "\n", "[API Documentation](https://cityofphiladelphia.github.io/carto-api-explorer/#shootings)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "tags": [] }, "outputs": [], "source": [ "# The CARTO API endpoint\n", "CARTO_URL = \"https://phl.carto.com/api/v2/sql\"\n", "\n", "# Select everything within the last year\n", "# NOTE: \"current_date\" is a SQL variable built in to the database\n", "WHERE = f\"date_ >= current_date - {MAX_DAYS}\"\n", "\n", "# The query parameters\n", "params = {\"q\": \"SELECT * FROM shootings\", \"format\": \"geojson\", \"where\": WHERE}\n", "\n", "# The request\n", "response = requests.get(CARTO_URL, params=params)\n", "\n", "# Make the GeoDataFrame\n", "DATA = gpd.GeoDataFrame.from_features(response.json(), crs=\"EPSG:4326\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Preprocess the data\n", "\n", "Do some preprocessing to clean up the data and format some columns." ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "tags": [] }, "outputs": [], "source": [ "# Remove entries with missing values\n", "DATA = DATA.dropna(subset=[\"point_x\", \"point_y\"])\n", "\n", "# Re-map the fatal column to Yes/No\n", "DATA[\"fatal\"] = DATA[\"fatal\"].map({0: \"No\", 1: \"Yes\"})\n", "\n", "# Remove entries where fatal is NaN\n", "DATA = DATA.dropna(subset=[\"fatal\"])\n", "\n", "# Parse the date_ column into a valid Datetime object\n", "DATA[\"date_\"] = pd.to_datetime(DATA[\"date_\"].str.slice(0, 10), format=\"%Y-%m-%d\")\n", "\n", "# Add longitude and latitude columns\n", "DATA[\"lat\"] = DATA.geometry.y\n", "DATA[\"lng\"] = DATA.geometry.x" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Build the app\n", "\n", "We'll define our app as a custom Python class that defines the various components of our dashboard, which include:\n", "\n", "- The parameters we want the user to be able to change.\n", "- Functions to generate the various charts/maps in our dashboard, based on those input parameters.\n", "- The dependencies between our chart functions and parameters." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": {}, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.holoviews_exec.v0+json": "", "text/html": [ "
\n", "
\n", "
\n", "" ], "text/plain": [ "Row\n", " [0] Param(ParameterizedMetaclass, name='PhiladelphiaShootingsApp'..., widgets={'start_date': {'type': = self.start_date) & (data_date <= self.end_date)\n", " \n", " # Subset and select necessary columns\n", " subset = DATA.loc[mask]\n", " COLS = [\"age\", \"fatal\", \"lat\", \"lng\", \"date_\"]\n", " subset = subset[COLS]\n", " \n", " return subset\n", " \n", "\n", " def get_daily_shootings(self):\n", " \"\"\"\n", " Return a DataFrame with two columns ('date_', 'count')\n", " that gives the total number of shootings per day.\n", " \"\"\"\n", " # Filter by the selected date range\n", " df = self.filter_by_date_range()\n", "\n", " # Group by date\n", " grouper = pd.Grouper(freq=\"d\")\n", " return df.set_index(\"date_\").groupby(grouper).size().reset_index(name=\"count\")\n", "\n", " @pm.depends(\"start_date\", \"end_date\")\n", " def pane_daily_shootings_chart(self):\n", " \"\"\"\n", " Return an hvplot chart of daily shootings.\n", " \"\"\"\n", " # Get the daily shootings data\n", " N = self.get_daily_shootings()\n", "\n", " # Plot the line chart\n", " return N.hvplot.line(\n", " x=\"date_\",\n", " y=\"count\",\n", " color=\"#cfcfcf\",\n", " width=1200,\n", " height=300,\n", " )\n", "\n", " @pm.depends(\"start_date\", \"end_date\")\n", " def pane_heatmap(self):\n", " \"\"\"\n", " Return a Folium map with a heatmap showing the data within the selected date range.\n", " \"\"\"\n", " m = folium.Map(location=[39.99, -75.13], tiles=\"Cartodb Positron\", zoom_start=12)\n", " data = self.filter_by_date_range()\n", " coordinates = data[[\"lat\", \"lng\"]].values\n", " HeatMap(coordinates).add_to(m)\n", " return pn.pane.plot.Folium(m, height=600)\n", "\n", " @pm.depends(\"start_date\", \"end_date\")\n", " def pane_summary_text(self):\n", " \"\"\"\n", " Get a summary of the number of shootings and homicides.\n", " \"\"\"\n", " data = self.filter_by_date_range()\n", " shootings = len(data)\n", " homicides = (data.fatal == \"Yes\").sum()\n", " t = f\"

There have been {shootings:,} shootings and {homicides:,} homicides between {self.start_date:%Y-%m-%d} and {self.end_date:%Y-%m-%d}.

\"\n", " return pn.pane.HTML(t, width=550)\n", "\n", " @pm.depends(\"start_date\", \"end_date\")\n", " def pane_altair_hist(self):\n", " \"\"\"\n", " Return an Altair histogram of shootings by age.\n", " \"\"\"\n", " data = self.filter_by_date_range()\n", " chart = (\n", " alt.Chart(data)\n", " .mark_bar()\n", " .encode(\n", " x=alt.X(\"age:Q\", bin=True, scale=alt.Scale(domain=(0, 100))),\n", " y=\"count()\",\n", " color=\"fatal:N\",\n", " tooltip=[\"count()\", \"age\", \"fatal\"],\n", " )\n", " .properties(\n", " width=400, height=400, title=\"Number of Shootings by Victim's Age\"\n", " )\n", " )\n", " return pn.pane.Vega(chart, width=600)\n", "\n", "# Replace `days` slider with date range picker in your dashboard layout\n", "pn.Row(\n", " pn.Param(\n", " PhiladelphiaShootingsApp.param,\n", " widgets={\n", " \"start_date\": {\"type\": pn.widgets.DatePicker},\n", " \"end_date\": {\"type\": pn.widgets.DatePicker},\n", " },\n", " )\n", ")\n" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "app = PhiladelphiaShootingsApp(name=\"\")" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "tags": [] }, "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", " \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", " \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", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
agefatallatlngdate_
3026No40.025375-75.1371332024-11-09
3235No40.023584-75.1530752024-11-27
3620No40.054625-75.1512512024-06-09
4715No40.028639-75.1431362024-06-14
4815No40.028639-75.1431362024-06-14
..................
1634923No39.952611-75.1660642024-09-10
1635039Yes40.042000-75.0618062024-11-06
1635242No39.951111-75.1527842024-10-04
1635934No40.029046-75.2106742024-08-30
1636234No40.079412-75.0691792024-06-26
\n", "

548 rows × 5 columns

\n", "
" ], "text/plain": [ " age fatal lat lng date_\n", "30 26 No 40.025375 -75.137133 2024-11-09\n", "32 35 No 40.023584 -75.153075 2024-11-27\n", "36 20 No 40.054625 -75.151251 2024-06-09\n", "47 15 No 40.028639 -75.143136 2024-06-14\n", "48 15 No 40.028639 -75.143136 2024-06-14\n", "... .. ... ... ... ...\n", "16349 23 No 39.952611 -75.166064 2024-09-10\n", "16350 39 Yes 40.042000 -75.061806 2024-11-06\n", "16352 42 No 39.951111 -75.152784 2024-10-04\n", "16359 34 No 40.029046 -75.210674 2024-08-30\n", "16362 34 No 40.079412 -75.069179 2024-06-26\n", "\n", "[548 rows x 5 columns]" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "app.filter_by_date_range()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Layout our Panel object: Bootstrap template\n", "\n", "We can use a combination of the `Column()` and `Row()` objects in Panel to create the layout in the main component.\n", "\n", "We'll also use the [Bootstrap template](https://panel.holoviz.org/reference/templates/Bootstrap.html) to improve the aesthetics of the user interface.\n", "\n", "\n", "- The `app.param` is an automatically generated set of widgets that corresponds to our `param` parameters\n", "- The charts are specified as the functions of our main application, e.g., app.bar_chart is the function that will return our bar chart.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Create a text HTML element to show instructions below the daily shootings chart and the title of the app:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "panel = pn.template.BootstrapTemplate(\n", " title=\"Recent Shootings in Philadelphia\",\n", " sidebar_width=0, # No sidebar needed for this app\n", ")" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/Users/delmelle/miniforge3/lib/python3.10/site-packages/altair/utils/core.py:384: FutureWarning: the convert_dtype parameter is deprecated and will be removed in a future version. Do ``ser.astype(object).apply()`` instead if you want ``convert_dtype=False``.\n", " col = df[col_name].apply(to_list_if_array, convert_dtype=False)\n", "/Users/delmelle/miniforge3/lib/python3.10/site-packages/altair/utils/core.py:384: FutureWarning: the convert_dtype parameter is deprecated and will be removed in a future version. Do ``ser.astype(object).apply()`` instead if you want ``convert_dtype=False``.\n", " col = df[col_name].apply(to_list_if_array, convert_dtype=False)\n" ] } ], "source": [ "# Append the content to the main part of the dashboard\n", "panel.main.append(\n", " pn.Column(\n", " pn.Row(app.pane_summary_text, app.param),\n", " pn.Row(app.pane_altair_hist, app.pane_heatmap),\n", " pn.Row(app.pane_daily_shootings_chart, align=\"center\"),\n", " )\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Call servable() and render our Panel object\n", "\n", "- The final step is to call the `.servable()` function\n", "- This will render the dashboard directly in the notebook\n", "- It also enables the notebook to be served from `localhost`.\n", "\n", "
\n", "Since we're using a template, the dashboard won't render properly in the notebook! You'll need to run it from the command line (Miniforge Prompt or Terminal).\n", "
\n", "\n", "\n", "From the command line, we will run:\n", "\n", "```\n", "panel serve --show shootingApp.ipynb\n", "```\n", "\n", "And see the app live at: `http://localhost:5006/app2`" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "tags": [] }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/Users/delmelle/miniforge3/lib/python3.10/site-packages/altair/utils/core.py:384: FutureWarning: the convert_dtype parameter is deprecated and will be removed in a future version. Do ``ser.astype(object).apply()`` instead if you want ``convert_dtype=False``.\n", " col = df[col_name].apply(to_list_if_array, convert_dtype=False)\n", "/Users/delmelle/miniforge3/lib/python3.10/site-packages/altair/utils/core.py:384: FutureWarning: the convert_dtype parameter is deprecated and will be removed in a future version. Do ``ser.astype(object).apply()`` instead if you want ``convert_dtype=False``.\n", " col = df[col_name].apply(to_list_if_array, convert_dtype=False)\n", "/Users/delmelle/miniforge3/lib/python3.10/site-packages/altair/utils/core.py:384: FutureWarning: the convert_dtype parameter is deprecated and will be removed in a future version. Do ``ser.astype(object).apply()`` instead if you want ``convert_dtype=False``.\n", " col = df[col_name].apply(to_list_if_array, convert_dtype=False)\n", "/Users/delmelle/miniforge3/lib/python3.10/site-packages/altair/utils/core.py:384: FutureWarning: the convert_dtype parameter is deprecated and will be removed in a future version. Do ``ser.astype(object).apply()`` instead if you want ``convert_dtype=False``.\n", " col = df[col_name].apply(to_list_if_array, convert_dtype=False)\n", "/Users/delmelle/miniforge3/lib/python3.10/site-packages/altair/utils/core.py:384: FutureWarning: the convert_dtype parameter is deprecated and will be removed in a future version. Do ``ser.astype(object).apply()`` instead if you want ``convert_dtype=False``.\n", " col = df[col_name].apply(to_list_if_array, convert_dtype=False)\n", "/Users/delmelle/miniforge3/lib/python3.10/site-packages/altair/utils/core.py:384: FutureWarning: the convert_dtype parameter is deprecated and will be removed in a future version. Do ``ser.astype(object).apply()`` instead if you want ``convert_dtype=False``.\n", " col = df[col_name].apply(to_list_if_array, convert_dtype=False)\n" ] }, { "data": {}, "metadata": {}, "output_type": "display_data" }, { "data": {}, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.holoviews_exec.v0+json": "", "text/html": [ "\n", "\n", " \n", " \n", " Panel App\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", "
\n", "
\n", "
\n", "\t\n", "\t
\n", "\t
\n", "
\n", "
\n", "
\n", "
\n", "\n", "
\n", "
\n", "
\n", "
\n", "\n", "\n", " \n", " \n", " \n", " \n", "" ], "text/plain": [ "BootstrapTemplate\n", " [js_area] HTML(None, height=0, margin=0, sizing_mode='fixed', width=0)\n", " [actions] BootstrapTemplateActions()\n", " [browser_info] BrowserInfo(dark_mode=False, device_pixel_ratio=2.2222222222222223, language='en-US', timezone='America/New_York', timezone_offset=300, webdriver=False, webgl=True)\n", " [busy_indicator] LoadingSpinner(height=20, width=20)\n", " [main-5118059248] Column\n", " [0] Row\n", " [0] ParamMethod(method, _pane=HTML, defer_load=False)\n", " [1] Column(margin=(5, 10))\n", " [0] StaticText(value='')\n", " [1] DatePicker(name='Start date', value=datetime.date(2024, 6, 8))\n", " [2] DatePicker(name='End date', value=datetime.date(2024, ...)\n", " [1] Row\n", " [0] ParamMethod(method, _pane=Vega, defer_load=False)\n", " [1] ParamMethod(method, _pane=Folium, defer_load=False)\n", " [2] Row(align='center')\n", " [0] ParamMethod(method, _pane=HoloViews, defer_load=False)" ] }, "execution_count": 12, "metadata": { "application/vnd.holoviews_exec.v0+json": { "id": "9b5211ef-f8c9-477b-9d3e-86a1de443650" } }, "output_type": "execute_result" } ], "source": [ "panel.servable()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.10.12" } }, "nbformat": 4, "nbformat_minor": 4 }