{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Lesson 27: JavaScript for stand-alone Bokeh apps\n", "\n", "
" ] }, { "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", " const 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", " const JS_MIME_TYPE = 'application/javascript';\n", " const HTML_MIME_TYPE = 'text/html';\n", " const EXEC_MIME_TYPE = 'application/vnd.bokehjs_exec.v0+json';\n", " const CLASS_NAME = 'output_bokeh rendered_html';\n", "\n", " /**\n", " * Render data to the DOM node\n", " */\n", " function render(props, node) {\n", " const 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", " const cell = handle.cell;\n", "\n", " const id = cell.output_area._bokeh_element_id;\n", " const 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", " const cmd_clean = \"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_clean, {\n", " iopub: {\n", " output: function(msg) {\n", " const 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", " const cmd_destroy = \"import bokeh.io.notebook as ion; ion.destroy_server('\" + server_id + \"')\";\n", " cell.notebook.kernel.execute(cmd_destroy);\n", " }\n", " }\n", "\n", " /**\n", " * Handle when a new output is added\n", " */\n", " function handleAddOutput(event, handle) {\n", " const output_area = handle.output_area;\n", " const output = handle.output;\n", "\n", " // limit handleAddOutput to display_data with EXEC_MIME_TYPE content only\n", " if ((output.output_type != \"display_data\") || (!Object.prototype.hasOwnProperty.call(output.data, EXEC_MIME_TYPE))) {\n", " return\n", " }\n", "\n", " const 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", " const bk_div = document.createElement(\"div\");\n", " bk_div.innerHTML = output.data[HTML_MIME_TYPE];\n", " const script_attrs = bk_div.children[0].attributes;\n", " for (let 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", " const 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", " const 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", " const events = require('base/js/events');\n", " const 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", " const 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", " const el = document.getElementById(\"1002\");\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(url) {\n", " console.error(\"failed to load \" + url);\n", " }\n", "\n", " for (let i = 0; i < css_urls.length; i++) {\n", " const url = css_urls[i];\n", " const element = document.createElement(\"link\");\n", " element.onload = on_load;\n", " element.onerror = on_error.bind(null, url);\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", " for (let i = 0; i < js_urls.length; i++) {\n", " const url = js_urls[i];\n", " const element = document.createElement('script');\n", " element.onload = on_load;\n", " element.onerror = on_error.bind(null, url);\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", " };\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", " const js_urls = [\"https://cdn.bokeh.org/bokeh/release/bokeh-2.4.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-gl-2.4.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.4.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.4.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-mathjax-2.4.2.min.js\"];\n", " const css_urls = [];\n", " \n", "\n", " const 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 (let 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", " const cell = $(document.getElementById(\"1002\")).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 const 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 const 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 const el = document.getElementById(\"1002\");\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(url) {\n console.error(\"failed to load \" + url);\n }\n\n for (let i = 0; i < css_urls.length; i++) {\n const url = css_urls[i];\n const element = document.createElement(\"link\");\n element.onload = on_load;\n element.onerror = on_error.bind(null, url);\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 for (let i = 0; i < js_urls.length; i++) {\n const url = js_urls[i];\n const element = document.createElement('script');\n element.onload = on_load;\n element.onerror = on_error.bind(null, url);\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 };\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 const js_urls = [\"https://cdn.bokeh.org/bokeh/release/bokeh-2.4.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-gl-2.4.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.4.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.4.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-mathjax-2.4.2.min.js\"];\n const css_urls = [];\n \n\n const 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 (let 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 const cell = $(document.getElementById(\"1002\")).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": [ "import pandas as pd\n", "import numpy as np\n", "import scipy.stats\n", "\n", "import bokeh.plotting\n", "import bokeh.io\n", "\n", "bokeh.io.output_notebook()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "As we have seen when [building dashboards](l25_dashboards.ipynb), we can build remarkable interactivity in our data displays, allowing for low-effort exploration of data sets. Bokeh allows us to link plots to Python code that can update our displays as we adjust parameters or select variables. We can also serve up apps to get only the data displays we like on their own browser tabs. I hope you recognize how powerful this is for exploring your data sets.\n", "\n", "There is a major drawback to this approach, though. In order to interactively explore using the dashboard, you need to have a Python interpreter running, either in the Jupyter notebook or when you serve your dashboards using `bokeh serve` on the command line. If you wanted to include an interactive plot in a publication, it would be nice to be able to interact with the plots/dashboard directly in the browser without the reader having to launch a Jupyter notebook or serve it up on their local machine (and have all of the necessary installations). In some cases, you will need the Python interpreter for sophisticated dashboards that do involved calculations. But in many cases, with just a little JavaScript, you can make beautiful interactive graphics rendered in pure HTML with JavaScript.\n", "\n", "(Note, though, that in coming years, [PyScript](https://pyscript.net) may change the game on this.)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## JavaScript and Bokeh\n", "\n", "We have been using Bokeh for rendering out plots and dashboards. As we have seen, Bokeh is a Python library for generating graphics that can be visualized and interacted with in the browser. In order to display the graphics and enable the interactions, Bokeh relies on its client-side [JavaScript](https://en.wikipedia.org/wiki/JavaScript) library, [BokehJS](https://docs.bokeh.org/en/latest/docs/dev_guide/bokehjs.html). It is this JavaScript library that handles all of the rendering, zooming, selecting, etc., as well has the widgets. The callback functions that get executed to update information about the plot based on changes in the widgets are in Python. This is what requires the Python interpreter to be running.\n", "\n", "Conveniently, Bokeh allows for pure JavaScript callbacks. And it turns out that if you know just a little JavaScript, you can make your dashboards have full functionality standing alone in the browser without Python running.\n", "\n", "So, in this lesson, we will learn a little JavaScript to make our dashboards be totally portable. We will not delve into the details of the language (that would require a complete bootcamp!), but will just give a little syntax. We will do it all in the context of making interactive plots. As you will see, a just a little JavaScript goes a long way!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Example 1: Exploring the Normal pdf\n", "\n", "In our [lesson on dashboarding](l25_dashboards.ipynb), we build an interactive plot of the probability density function (pdf) for the Normal distribution. We used the `scipy.stats` package to get the mathematical expression for the pdf. Since we will code it up in JavaScript, I write it here.\n", "\n", "\\begin{align}\n", "f(x;\\mu, \\sigma) = \\frac{\\mathrm{e}^{-(x-\\mu)^2/2\\sigma^2}}{\\sqrt{2\\pi\\sigma^2}}.\n", "\\end{align}\n", "\n", "I will not recreate the little dashboard we made in the dashboarding lesson for visualizing the Normal pdf, but so that it can stand alone. As a reminder, here is the code (sans imports) we used before to create the dashboard.\n", "\n", "```python\n", "# Parameters; we'll start with standard Normal\n", "mu = 0.0\n", "sigma = 1.0\n", "\n", "# Generate data\n", "x = np.linspace(-10, 10, 200)\n", "pdf = scipy.stats.norm.pdf(x, loc=mu, scale=sigma)\n", "\n", "# Column data source for plot\n", "source = bokeh.models.ColumnDataSource(dict(x=x, pdf=pdf))\n", "\n", "# Build figure\n", "p = bokeh.plotting.figure(\n", " frame_width=350,\n", " frame_height=200,\n", " x_axis_label='x',\n", " y_axis_label='f(x)',\n", " x_range=[-10, 10],\n", ")\n", "\n", "# Put line on plot\n", "p.line(source=source, x='x', y='pdf', line_width=2)\n", "\n", "# Sliders\n", "mu_slider = bokeh.models.Slider(title=\"µ\", start=-5.0, end=5.0, step=0.1, value=0.0, width=100)\n", "sigma_slider = bokeh.models.Slider(title=\"σ\", start=0.1, end=5.0, step=0.1, value=1.0, width=100)\n", "\n", "def norm_callback(attr, old, new):\n", " \"\"\"Callback for updating data in Normal PDF plot.\"\"\"\n", " # Pull the values off of each slider\n", " mu = mu_slider.value\n", " sigma = sigma_slider.value\n", " \n", " # Re-compute the y-values\n", " pdf = scipy.stats.norm.pdf(source.data['x'], loc=mu, scale=sigma)\n", " \n", " # Update the column data source\n", " source.data[\"pdf\"] = pdf\n", "\n", "\n", "# Connect sliders\n", "mu_slider.on_change('value', norm_callback)\n", "sigma_slider.on_change('value', norm_callback)\n", "\n", "# Put the sliders one on top of the other\n", "slider_layout = bokeh.layouts.column(\n", " bokeh.layouts.Spacer(height=30),\n", " mu_slider,\n", " bokeh.layouts.Spacer(height=15),\n", " sigma_slider, \n", ")\n", "\n", "# Put the sliders to the right of the plot\n", "norm_layout = bokeh.layouts.row(\n", " p,\n", " bokeh.layouts.Spacer(width=15),\n", " slider_layout\n", ")\n", "\n", "\n", "def norm_app(doc):\n", " doc.add_root(norm_layout)\n", "\n", " \n", "bokeh.io.show(norm_app, notebook_url=notebook_url) \n", "```\n", "\n", "Now, let's build the dashboard with a JavaScript callback so it can stand alone with a Python interpreter running. First, the setup of the setup of the sliders, data, and figure are the same as we would normally do." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "# Initial setup of the sliders is the same\n", "mu_slider = bokeh.models.Slider(title=\"µ\", start=-5, end=5, step=0.1, value=0)\n", "sigma_slider = bokeh.models.Slider(title=\"σ\", start=0.1, end=5, step=0.1, value=1)\n", "\n", "# Setup of x and y values is also the same\n", "x = np.linspace(-10, 10, 200)\n", "pdf = scipy.stats.norm.pdf(x, loc=0, scale=1)\n", "\n", "# Set up the plot as a Bokeh figure\n", "p = bokeh.plotting.figure(\n", " frame_width=300,\n", " frame_height=200,\n", " x_axis_label=\"x\",\n", " y_axis_label=\"f(x; μ, σ)\",\n", " x_range=[-10, 10],\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next, we set up a `ColumnDataSource` when we build the plot so we have access to it when manipulate the sliders and use a JavaScript callback." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "# Use a ColumnDataSource\n", "source = bokeh.models.ColumnDataSource(dict(x=x, pdf=pdf))\n", "p.line(source=source, x=\"x\", y=\"pdf\", line_width=2);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Laying out the sliders and plot is the same as before." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "# Laying out the widgets is the same\n", "slider_layout = bokeh.layouts.column(\n", " bokeh.layouts.Spacer(height=30),\n", " mu_slider,\n", " bokeh.layouts.Spacer(height=15),\n", " sigma_slider,\n", " width=200,\n", ")\n", "\n", "# Lay out with the plot and widgets\n", "norm_layout = bokeh.layouts.row(p, bokeh.layouts.Spacer(width=15), slider_layout)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, we need to write JavaScript code for the callback. Whenever a slider changes value, we want to recompute the values of the Normal pdf. Here is JavaScript code to do that.\n", "\n", "```javascript\n", "function normalPDF(x, mu, sigma) {\n", " let expArg = (x - mu) ** 2 / 2.0 / sigma ** 2;\n", " return Math.exp(-expArg) / sigma / Math.sqrt(2 * Math.PI);\n", "}\n", "\n", "// For convenience, get views into the ColumnDataSource data\n", "let x = source.data['x'];\n", "let pdf = source.data['pdf'];\n", "\n", "// Pull the values off of the sliders\n", "let mu = mu_slider.value;\n", "let sigma = sigma_slider.value;\n", "\n", "// Loop through and update\n", "let xLen = x.length;\n", "for (let i = 0; i < xLen; i++) {\n", " pdf[i] = normalPDF(x[i], mu, sigma);\n", "}\n", "\n", "// Once the ColumnDataSource is changed, we need to use its \n", "// .change.emit() method to update the plot\n", "source.change.emit();\n", "```\n", "\n", "Let's discuss the syntax. First, comments in JavaScript are preceded with `//`. Functions in JavaScript are declared like this:\n", "\n", "```javascript\n", "function funcName() {\n", " // function body\n", "}\n", "```\n", "\n", "The `function` keyword is followed by the function name, with its arguments in parentheses separated by commas. The function body is then contained between braces.\n", "\n", "Within the `normalPDF()` function, we make some calculations. First, we define a variable that is the argument for the exponentiation, $-(x-\\mu)^2/2\\sigma^2$. Note that whenever we use a new variable, it must be preceded by the keyword `let` (or `var`, but we will not get into the differences between those keywords). The arithmetic operators, including raise-to-power, are the same as in Python. We end each statement with a semicolon.\n", "\n", "Next comes the `return` statement. Its syntax is just like Python. The only difference in the return statement is that we need to use JavaScript's `Math` module to get access to the exponentiation and square root functions, and also to the value of π. Note that this function is _not_ vectorized. It assumes `x`, `mu`, and `sigma` are scalar valued and computes the value of the Normal pdf at that given value of `x`.\n", "\n", "Conveniently, accessing the `ColumnDataSource.data` attribute using JavaScript is exactly as in Python. For convenience in the above code, we create views into the `ColumnDataSource` using `let x = source.data['x'];` and `let pdf = source.data['pdf'];`.\n", "\n", "Next, we pull the values from the sliders. This is also done as in Python (except with the necessary `let`).\n", "\n", "Now that we have access to the data and the slider values, we need to loop through the data in the `ColumnDataSource` and update it according to the values of the sliders. A `for` loop in JavaScript typically has the following form.\n", "\n", "```javascript\n", "for (let i = 0; i < lastValueOfiYouWant; i++) {\n", " // body of for loop\n", "}\n", "```\n", "\n", "Inside the parenthetical after the `for` keyword are two semicolons. Before the first is an initialization. After the first semicolon is a conditional statement. The loop will continue so long as that conditional statement gives `true` (in JavaScript the keyword for truth is all lowercase, unlike in Python). Finally, after the second semicolon is the iteration statement. It is executed whenever a trip through the body of the loop concludes. The syntax `i++` is equivalent to Python's `i += 1`.\n", "\n", "So, the `for` loop in the above statement loops through each x-value in the plot and updates the value of the Normal pdf using the parameter values we have pulled off of the sliders.\n", "\n", "Finally, in order for the plot to update, you need to execute the `source.change.emit()` function, which pushes the updates of the `ColumnDataSource` to the rendered plot.\n", "\n", "This code is in JavaScript, so obviously the Python interpreter will not know what to do with it. It is not really used until things get handed off to the BokehJS library. So, we need to store the code as a Python string." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "# JavaScript code for the callback stored as a string\n", "jscode = \"\"\"\n", "function normalPDF(x, mu, sigma) {\n", " let expArg = (x - mu) ** 2 / 2.0 / sigma ** 2;\n", " return Math.exp(-expArg) / sigma / Math.sqrt(2 * Math.PI);\n", "}\n", "\n", "// For convenience, get views into the ColumnDataSource data\n", "let x = source.data['x'];\n", "let pdf = source.data['pdf'];\n", "\n", "// Pull the values off of the sliders\n", "let mu = mu_slider.value;\n", "let sigma = sigma_slider.value;\n", "\n", "// Loop through and update\n", "let xLen = x.length;\n", "for (let i = 0; i < xLen; i++) {\n", " pdf[i] = normalPDF(x[i], mu, sigma);\n", "}\n", "\n", "// Once the ColumnDataSource is changed, we need to use its \n", "// .change.emit() method to update the plot\n", "source.change.emit();\n", "\"\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that we have the code, we need to connect it to the sliders. That is, we need to let the slider objects know that when they change, the JavaScript code should be triggered." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "args = dict(source=source, mu_slider=mu_slider, sigma_slider=sigma_slider)\n", "\n", "# Connect the callback to the sliders\n", "mu_slider.js_on_change(\"value\", bokeh.models.CustomJS(code=jscode, args=args))\n", "sigma_slider.js_on_change(\"value\", bokeh.models.CustomJS(code=jscode, args=args))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `js_on_change()` method links the sliders to the JavaScript code. The first argument of the `js_on_change()` method is what is changing that will trigger the callback. In this case, we want the callback to be triggered whenever the value of the slider changes. The second argument is a Bokeh `CustomJS` object. This is constructed by specifying the code as a string and the arguments that will be passed to the JavaScript code (in this case the `ColumnDataSource` and the two sliders).\n", "\n", "Note that if we used Panel-based sliders instead of the Bokeh sliders we are using here, the syntax is\n", "\n", "```python\n", "slider_created_using_panel.jscallback(value=jscode, args=args)\n", "```\n", "\n", "Now we are ready to check out our layout! We only need to call `bokeh.io.show()` and do not need to supply a `notebook_url` argument because there are no Python callbacks." ] }, { "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", " const docs_json = {\"35b84f01-526c-4c09-ae6a-40a743e1f57a\":{\"defs\":[],\"roots\":{\"references\":[{\"attributes\":{\"children\":[{\"id\":\"1005\"},{\"id\":\"1046\"},{\"id\":\"1045\"}]},\"id\":\"1047\",\"type\":\"Row\"},{\"attributes\":{\"axis_label\":\"x\",\"coordinates\":null,\"formatter\":{\"id\":\"1056\"},\"group\":null,\"major_label_policy\":{\"id\":\"1057\"},\"ticker\":{\"id\":\"1015\"}},\"id\":\"1014\",\"type\":\"LinearAxis\"},{\"attributes\":{\"args\":{\"mu_slider\":{\"id\":\"1003\"},\"sigma_slider\":{\"id\":\"1004\"},\"source\":{\"id\":\"1036\"}},\"code\":\"\\nfunction normalPDF(x, mu, sigma) {\\n let expArg = (x - mu) ** 2 / 2.0 / sigma ** 2;\\n return Math.exp(-expArg) / sigma / Math.sqrt(2 * Math.PI);\\n}\\n\\n// For convenience, get views into the ColumnDataSource data\\nlet x = source.data['x'];\\nlet pdf = source.data['pdf'];\\n\\n// Pull the values off of the sliders\\nlet mu = mu_slider.value;\\nlet sigma = sigma_slider.value;\\n\\n// Loop through and update\\nlet xLen = x.length;\\nfor (let i = 0; i < xLen; i++) {\\n pdf[i] = normalPDF(x[i], mu, sigma);\\n}\\n\\n// Once the ColumnDataSource is changed, we need to use its \\n// .change.emit() method to update the plot\\nsource.change.emit();\\n\"},\"id\":\"1049\",\"type\":\"CustomJS\"},{\"attributes\":{\"end\":5,\"js_property_callbacks\":{\"change:value\":[{\"id\":\"1049\"}]},\"start\":0.1,\"step\":0.1,\"title\":\"\\u03c3\",\"value\":1},\"id\":\"1004\",\"type\":\"Slider\"},{\"attributes\":{},\"id\":\"1058\",\"type\":\"UnionRenderers\"},{\"attributes\":{\"end\":5,\"js_property_callbacks\":{\"change:value\":[{\"id\":\"1048\"}]},\"start\":-5,\"step\":0.1,\"title\":\"\\u00b5\",\"value\":0},\"id\":\"1003\",\"type\":\"Slider\"},{\"attributes\":{\"line_alpha\":0.2,\"line_color\":\"#1f77b4\",\"line_width\":2,\"x\":{\"field\":\"x\"},\"y\":{\"field\":\"pdf\"}},\"id\":\"1040\",\"type\":\"Line\"},{\"attributes\":{},\"id\":\"1054\",\"type\":\"AllLabels\"},{\"attributes\":{\"below\":[{\"id\":\"1014\"}],\"center\":[{\"id\":\"1017\"},{\"id\":\"1021\"}],\"frame_height\":200,\"frame_width\":300,\"left\":[{\"id\":\"1018\"}],\"renderers\":[{\"id\":\"1041\"}],\"title\":{\"id\":\"1050\"},\"toolbar\":{\"id\":\"1029\"},\"x_range\":{\"id\":\"1006\"},\"x_scale\":{\"id\":\"1010\"},\"y_range\":{\"id\":\"1008\"},\"y_scale\":{\"id\":\"1012\"}},\"id\":\"1005\",\"subtype\":\"Figure\",\"type\":\"Plot\"},{\"attributes\":{\"axis\":{\"id\":\"1014\"},\"coordinates\":null,\"group\":null,\"ticker\":null},\"id\":\"1017\",\"type\":\"Grid\"},{\"attributes\":{},\"id\":\"1015\",\"type\":\"BasicTicker\"},{\"attributes\":{},\"id\":\"1012\",\"type\":\"LinearScale\"},{\"attributes\":{\"coordinates\":null,\"data_source\":{\"id\":\"1036\"},\"glyph\":{\"id\":\"1038\"},\"group\":null,\"hover_glyph\":null,\"muted_glyph\":{\"id\":\"1040\"},\"nonselection_glyph\":{\"id\":\"1039\"},\"view\":{\"id\":\"1042\"}},\"id\":\"1041\",\"type\":\"GlyphRenderer\"},{\"attributes\":{},\"id\":\"1023\",\"type\":\"WheelZoomTool\"},{\"attributes\":{\"axis_label\":\"f(x; \\u03bc, \\u03c3)\",\"coordinates\":null,\"formatter\":{\"id\":\"1053\"},\"group\":null,\"major_label_policy\":{\"id\":\"1054\"},\"ticker\":{\"id\":\"1019\"}},\"id\":\"1018\",\"type\":\"LinearAxis\"},{\"attributes\":{\"bottom_units\":\"screen\",\"coordinates\":null,\"fill_alpha\":0.5,\"fill_color\":\"lightgrey\",\"group\":null,\"left_units\":\"screen\",\"level\":\"overlay\",\"line_alpha\":1.0,\"line_color\":\"black\",\"line_dash\":[4,4],\"line_width\":2,\"right_units\":\"screen\",\"syncable\":false,\"top_units\":\"screen\"},\"id\":\"1028\",\"type\":\"BoxAnnotation\"},{\"attributes\":{\"height\":15},\"id\":\"1044\",\"type\":\"Spacer\"},{\"attributes\":{\"children\":[{\"id\":\"1043\"},{\"id\":\"1003\"},{\"id\":\"1044\"},{\"id\":\"1004\"}],\"width\":200},\"id\":\"1045\",\"type\":\"Column\"},{\"attributes\":{},\"id\":\"1026\",\"type\":\"ResetTool\"},{\"attributes\":{\"height\":30},\"id\":\"1043\",\"type\":\"Spacer\"},{\"attributes\":{},\"id\":\"1025\",\"type\":\"SaveTool\"},{\"attributes\":{\"overlay\":{\"id\":\"1028\"}},\"id\":\"1024\",\"type\":\"BoxZoomTool\"},{\"attributes\":{},\"id\":\"1022\",\"type\":\"PanTool\"},{\"attributes\":{},\"id\":\"1027\",\"type\":\"HelpTool\"},{\"attributes\":{\"line_alpha\":0.1,\"line_color\":\"#1f77b4\",\"line_width\":2,\"x\":{\"field\":\"x\"},\"y\":{\"field\":\"pdf\"}},\"id\":\"1039\",\"type\":\"Line\"},{\"attributes\":{},\"id\":\"1053\",\"type\":\"BasicTickFormatter\"},{\"attributes\":{\"args\":{\"mu_slider\":{\"id\":\"1003\"},\"sigma_slider\":{\"id\":\"1004\"},\"source\":{\"id\":\"1036\"}},\"code\":\"\\nfunction normalPDF(x, mu, sigma) {\\n let expArg = (x - mu) ** 2 / 2.0 / sigma ** 2;\\n return Math.exp(-expArg) / sigma / Math.sqrt(2 * Math.PI);\\n}\\n\\n// For convenience, get views into the ColumnDataSource data\\nlet x = source.data['x'];\\nlet pdf = source.data['pdf'];\\n\\n// Pull the values off of the sliders\\nlet mu = mu_slider.value;\\nlet sigma = sigma_slider.value;\\n\\n// Loop through and update\\nlet xLen = x.length;\\nfor (let i = 0; i < xLen; i++) {\\n pdf[i] = normalPDF(x[i], mu, sigma);\\n}\\n\\n// Once the ColumnDataSource is changed, we need to use its \\n// .change.emit() method to update the plot\\nsource.change.emit();\\n\"},\"id\":\"1048\",\"type\":\"CustomJS\"},{\"attributes\":{\"width\":15},\"id\":\"1046\",\"type\":\"Spacer\"},{\"attributes\":{\"source\":{\"id\":\"1036\"}},\"id\":\"1042\",\"type\":\"CDSView\"},{\"attributes\":{\"coordinates\":null,\"group\":null},\"id\":\"1050\",\"type\":\"Title\"},{\"attributes\":{},\"id\":\"1056\",\"type\":\"BasicTickFormatter\"},{\"attributes\":{\"axis\":{\"id\":\"1018\"},\"coordinates\":null,\"dimension\":1,\"group\":null,\"ticker\":null},\"id\":\"1021\",\"type\":\"Grid\"},{\"attributes\":{},\"id\":\"1057\",\"type\":\"AllLabels\"},{\"attributes\":{},\"id\":\"1019\",\"type\":\"BasicTicker\"},{\"attributes\":{\"tools\":[{\"id\":\"1022\"},{\"id\":\"1023\"},{\"id\":\"1024\"},{\"id\":\"1025\"},{\"id\":\"1026\"},{\"id\":\"1027\"}]},\"id\":\"1029\",\"type\":\"Toolbar\"},{\"attributes\":{\"line_color\":\"#1f77b4\",\"line_width\":2,\"x\":{\"field\":\"x\"},\"y\":{\"field\":\"pdf\"}},\"id\":\"1038\",\"type\":\"Line\"},{\"attributes\":{},\"id\":\"1008\",\"type\":\"DataRange1d\"},{\"attributes\":{},\"id\":\"1010\",\"type\":\"LinearScale\"},{\"attributes\":{\"data\":{\"pdf\":{\"__ndarray__\":\"2tW0RmhBVztb3BOuUJtvO3rj/3s4Q4U7kuDXp/dRnDs0+Cfpr6uyO9+sw5/fXsg73VCEGbF93zuibVVuMiT0O5ossUtxgQk8r28SllP5HzxKg+n9AtczPJ7Yno66X0g8P8CDy6qkXTyZaKKbPNhxPMaK74i2RIU8TqNEpyIYmTw3xBS8kE+tPElsTNok8sA8ZFnlKrxl0zwcQIxd/vrlPPN0CRU6qPg8HBAaIb5hCz1bQsWNGhoePUivDmxAYTA92RpXUKClQT3oUs/qLdJSPYy49o8V32M9mLZyzATFdD0IJ+TQfn2FPbvdRCcqA5Y9/N9doRJSpj2LMhgT22e2PVjxDXDbQ8Y9hbIINSnn1T0fVAOHiVTlPRHSpP9NkPQ9THpclx6gAz6IDhVetIoSPlaUoKGJVyE+bhwbqoQOMD55f0WhRG89Pjmczs1KtUo+Q3mbdp79Vz7XX7ElSVVlPlIaWaSCx3I+w4XZvHddgD67x4VjYDyMPubGMlQjHZg+E9DnZ/d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nxnEoSQEbmSxOHsRJAWGS+NHEYE0Bq4jBWW38TQHxgo3dF5hNAjt4VmS9NFECgXIi6GbQUQLLa+tsDGxVAxFht/e2BFUDW1t8e2OgVQOhUUkDCTxZA+tLEYay2FkAMUTeDlh0XQB7PqaSAhBdAME0cxmrrF0BEy47nVFIYQFRJAQk/uRhAaMdzKikgGUB4ReZLE4cZQIzDWG397RlAnEHLjudUGkCwvz2w0bsaQMA9sNG7IhtA1Lsi86WJG0DkOZUUkPAbQPi3BzZ6VxxACDZ6V2S+HEActOx4TiUdQCwyX5o4jB1AQLDRuyLzHUBQLkTdDFoeQGSstv72wB5AdCopIOEnH0CIqJtBy44fQJgmDmO19R9AVlJAwk8uIEBekfnSxGEgQGjQsuM5lSBAcA9s9K7IIEB6TiUFJPwgQIKN3hWZLyFAjMyXJg5jIUCUC1E3g5YhQJ5KCkj4ySFAponDWG39IUCwyHxp4jAiQLgHNnpXZCJAwkbvisyXIkDKhaibQcsiQNTEYay2/iJA3AMbvSsyI0DmQtTNoGUjQO6Bjd4VmSNA+MBG74rMI0AAAAAAAAAkQA==\",\"dtype\":\"float64\",\"order\":\"little\",\"shape\":[200]}},\"selected\":{\"id\":\"1059\"},\"selection_policy\":{\"id\":\"1058\"}},\"id\":\"1036\",\"type\":\"ColumnDataSource\"},{\"attributes\":{\"end\":10,\"start\":-10},\"id\":\"1006\",\"type\":\"Range1d\"},{\"attributes\":{},\"id\":\"1059\",\"type\":\"Selection\"}],\"root_ids\":[\"1047\"]},\"title\":\"Bokeh Application\",\"version\":\"2.4.2\"}};\n", " const render_items = [{\"docid\":\"35b84f01-526c-4c09-ae6a-40a743e1f57a\",\"root_ids\":[\"1047\"],\"roots\":{\"1047\":\"19f38048-5c38-4da3-af9f-99da61cbfd55\"}}];\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", " let attempts = 0;\n", " const 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": "1047" } }, "output_type": "display_data" } ], "source": [ "# Display the layout\n", "bokeh.io.show(norm_layout)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is more or less the same about of work we did creating the dashboard as in the previous lesson except the callbacks were written in JavaScript and linked using `js_on_change()`.\n", "\n", "Writing callbacks in a new language is not trivial. But, I hope you can see that it's not _too_ bad to code up the JavaScript. The payoff is big. You get a stand-alone interactive plot that _anyone_ can view and play with in their browser without even having Python installed.\n", "\n", "Let's now make that HTML document." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'/Users/bois/Dropbox/git/programming_bootcamp/2022/content/lessons/normal_pdf_app.html'" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bokeh.io.save(norm_layout, \"normal_pdf_app.html\", resources=bokeh.resources.CDN, title=\"Normal PDF\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can again ignore the warnings. We now have our stand-alone app!\n", "\n", "(Note that if you wanted to save a Panel layout to HTML, the syntax is `layout_made_with_panel.save(\"filename.html\")`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exploring a data set\n", "\n", "In the [dashboarding lesson](l25_dashboards.ipynb), we used data from the [Beattie, et al.](https://doi.org/10.1098/rsos.160321) study of how sleep deprivation affects facial matching ability to build a dashboard to explore a data set. Here, I will demonstrate how to build the same dashboard, as a standalone app with JavaScript callbacks. Such a plot could appear in a publication with full interactivity for all readers.\n", "\n", "Of course, we'll start with loading in the data." ] }, { "cell_type": "code", "execution_count": 9, "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", " \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", "
participant numbergenderagecorrect hit percentagecorrect reject percentagepercent correctconfidence when correct hitconfidence when incorrect hitconfidence when correct rejectconfidence when incorrect rejectconfidence when correctconfidence when incorrectscipsqiessinsomnia
08f39658072.591.090.093.083.593.090.09132True
116m42909090.075.555.570.550.075.050.04117True
218f31909592.589.590.086.081.089.088.01093True
322f351007587.589.5NaN71.080.088.080.013820True
427f74606562.568.549.061.049.065.049.013912True
\n", "
" ], "text/plain": [ " participant number gender age correct hit percentage \\\n", "0 8 f 39 65 \n", "1 16 m 42 90 \n", "2 18 f 31 90 \n", "3 22 f 35 100 \n", "4 27 f 74 60 \n", "\n", " correct reject percentage percent correct confidence when correct hit \\\n", "0 80 72.5 91.0 \n", "1 90 90.0 75.5 \n", "2 95 92.5 89.5 \n", "3 75 87.5 89.5 \n", "4 65 62.5 68.5 \n", "\n", " confidence when incorrect hit confidence when correct reject \\\n", "0 90.0 93.0 \n", "1 55.5 70.5 \n", "2 90.0 86.0 \n", "3 NaN 71.0 \n", "4 49.0 61.0 \n", "\n", " confidence when incorrect reject confidence when correct \\\n", "0 83.5 93.0 \n", "1 50.0 75.0 \n", "2 81.0 89.0 \n", "3 80.0 88.0 \n", "4 49.0 65.0 \n", "\n", " confidence when incorrect sci psqi ess insomnia \n", "0 90.0 9 13 2 True \n", "1 50.0 4 11 7 True \n", "2 88.0 10 9 3 True \n", "3 80.0 13 8 20 True \n", "4 49.0 13 9 12 True " ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df = pd.read_csv('data/gfmt_sleep.csv', na_values='*')\n", "\n", "# Add column for insomnia\n", "df['insomnia'] = df['sci'] <= 16\n", "\n", "df.head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To build the dashboard, we will start by setting up the selectors, one for the x-axis variable, one for the y-axis variable, and one for how we will color the glyphs. Again, this is the same code as before." ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "# Options for x- and y- selector; omit part. num., gender, and insomnia\n", "xy_options = list(\n", " df.columns[~df.columns.isin([\"participant number\", \"gender\", \"insomnia\"])]\n", ")\n", "\n", "x_selector = bokeh.models.Select(\n", " title=\"x\", options=xy_options, value=\"percent correct\", width=200,\n", ")\n", "\n", "y_selector = bokeh.models.Select(\n", " title=\"y\", options=xy_options, value=\"confidence when correct\", width=200,\n", ")\n", "\n", "colorby_selector = bokeh.models.Select(\n", " title=\"color by\", options=[\"none\", \"gender\", \"insomnia\",], value=\"none\", width=200,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next, we can set up the `ColumnDataSource`. When we built the dashboard in the previous lesson, we had a single ColumnDataSource that got updated by pulling out of the data frame in the Python callbacks. Now, we will be using only JavaScript callbacks, and JavaScript does not know what a Pandas data frame is. Therefore, we create a *second* ColumnDataSource from the data frame that we can pull from to populate the ColumnDataSource that is used in the rendering of the plot.\n", "\n", "First, we make the source that is used in rendering. It is just as before." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "render_source = bokeh.models.ColumnDataSource(\n", " {\n", " \"x\": df[\"percent correct\"],\n", " \"y\": df[\"confidence when correct\"],\n", " \"color\": [\"#1f77b3\"] * len(df),\n", " }\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that we have the `ColumnDataSource` for rendering, we need to convert the data frame `df` into a `ColumnDataSource` so we can have access to it using JavaScript." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "source = bokeh.models.ColumnDataSource(df)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we can make our figure!" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "p = bokeh.plotting.figure(\n", " frame_height=250,\n", " frame_width=250,\n", " x_axis_label=\"percent correct\",\n", " y_axis_label=\"confidence when correct\",\n", ")\n", "\n", "circle = p.circle(\n", " source=render_source, x=\"x\", y=\"y\", fill_color=\"color\", line_color=\"color\",\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, we write our JavaScript code for the callbacks. These will happen whenever the selectors change. Following is the JavaScript code.\n", "\n", "```javascript\n", "// Extract what we want to color by from selector\n", "let colorby = colorby_selector.value;\n", "\n", "// View of the colors for convenience\n", "let colors = render_source.data['color'];\n", "\n", "// Convenient to have the number of data points\n", "let n = colors.length;\n", "\n", "// Update rendered data from full data set\n", "render_source.data['x'] = source.data[x_selector.value];\n", "render_source.data['y'] = source.data[y_selector.value];\n", "\n", "// Update colors\n", "if (colorby === 'none') {\n", " for (let i = 0; i < n; i++) {\n", " colors[i] = '#1f77b3';\n", " }\n", "}\n", "else if (colorby === 'gender') {\n", " for (let i = 0; i < n; i++) {\n", " if (source.data['gender'][i] === 'f') {\n", " colors[i] = '#1f77b3';\n", " }\n", " else {\n", " colors[i] = '#ff7e0e';\n", " }\n", " }\n", "}\n", "else if (colorby === 'insomnia') {\n", " for (let i = 0; i < n; i++) {\n", " if (source.data['insomnia'][i]) {\n", " colors[i] = '#1f77b3';\n", " }\n", " else {\n", " colors[i] = '#ff7e0e';\n", " }\n", " }\n", "}\n", "\n", "// Update axis labels to reflect what was selected\n", "xaxis[0].axis_label = x_selector.value;\n", "yaxis[0].axis_label = y_selector.value;\n", "\n", "render_source.change.emit();\n", "```\n", "\n", "Except for the `if` statements, which have new syntax, the code should be self-explanatory. There is the added wrinkle of the `xaxis` and `yaxis` variables, which we will have to pass into the JavaScript code as arguments. These are Bokeh `LinearAxis` objects that we need to access to update the axis labels for what we are plotting.\n", "\n", "In JavaScript, an `if`-`else` statement has the structure\n", "\n", "```c\n", "if (statement_returning_boolean) {\n", " // code to be executed if statement_returning_boolean is true\n", "}\n", "else if (another_statement_returning_boolean) {\n", " // code to be executed if another_statement_returning_boolean is true\n", "}\n", "else {\n", " // code to be executed if all booleans were false\n", "}\n", "```\n", "\n", "Note the use of `===` for the equals comparison operator. In JavaScript, if I use `a == b`, JavaScript tries to do type comparisons to compare things. `0 == ''` will evaluate `true`. The `===` operator means that there are no type comparisons. So, `0 === ''` evaluates `false`.\n", "\n", "Now that we have our JavaScript code, let's put it to use!" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "jscode = \"\"\"\n", "// Extract what we want to color by from selector\n", "let colorby = colorby_selector.value;\n", "\n", "// View of the colors for convenience\n", "let colors = render_source.data['color'];\n", "\n", "// Convenient to have the number of data points\n", "let n = colors.length;\n", "\n", "// New data\n", "render_source.data['x'] = source.data[x_selector.value];\n", "render_source.data['y'] = source.data[y_selector.value];\n", "\n", "// Update colors\n", "if (colorby === 'none') {\n", " for (let i = 0; i < n; i++) {\n", " colors[i] = '#1f77b3';\n", " }\n", "}\n", "else if (colorby === 'gender') {\n", " for (let i = 0; i < n; i++) {\n", " if (source.data['gender'][i] === 'f') {\n", " colors[i] = '#1f77b3';\n", " }\n", " else {\n", " colors[i] = '#ff7e0e';\n", " }\n", " }\n", "}\n", "else if (colorby === 'insomnia') {\n", " for (let i = 0; i < n; i++) {\n", " if (source.data['insomnia'][i]) {\n", " colors[i] = '#1f77b3';\n", " }\n", " else {\n", " colors[i] = '#ff7e0e';\n", " }\n", " }\n", "}\n", "\n", "// Update axis labels to reflect what was selected\n", "xaxis[0].axis_label = x_selector.value;\n", "yaxis[0].axis_label = y_selector.value;\n", "\n", "render_source.change.emit();\n", "\"\"\"\n", "\n", "args = dict(\n", " render_source=render_source,\n", " source=source,\n", " colorby_selector=colorby_selector,\n", " x_selector=x_selector,\n", " y_selector=y_selector,\n", " xaxis=p.xaxis,\n", " yaxis=p.yaxis,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that I have put both data sources, the selectors, and the `p.axis` and `p.yaxis` objects as arguments to the JavaScript code. Now we can link the callbacks." ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "colorby_selector.js_on_change(\"value\", bokeh.models.CustomJS(code=jscode, args=args))\n", "x_selector.js_on_change(\"value\", bokeh.models.CustomJS(code=jscode, args=args))\n", "y_selector.js_on_change(\"value\", bokeh.models.CustomJS(code=jscode, args=args))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And finally, let's lay it out!" ] }, { "cell_type": "code", "execution_count": 16, "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", " const docs_json = {\"62a9ed7b-63d4-441d-a11c-10a687ddd581\":{\"defs\":[],\"roots\":{\"references\":[{\"attributes\":{\"children\":[{\"id\":\"1243\"},{\"id\":\"1283\"},{\"id\":\"1286\"}]},\"id\":\"1287\",\"type\":\"Row\"},{\"attributes\":{\"bottom_units\":\"screen\",\"coordinates\":null,\"fill_alpha\":0.5,\"fill_color\":\"lightgrey\",\"group\":null,\"left_units\":\"screen\",\"level\":\"overlay\",\"line_alpha\":1.0,\"line_color\":\"black\",\"line_dash\":[4,4],\"line_width\":2,\"right_units\":\"screen\",\"syncable\":false,\"top_units\":\"screen\"},\"id\":\"1266\",\"type\":\"BoxAnnotation\"},{\"attributes\":{\"height\":15},\"id\":\"1284\",\"type\":\"Spacer\"},{\"attributes\":{\"data\":{\"color\":[\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#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AAMBQQAAAAAAAQFBAAAAAAACAVEAAAAAAAMBSQAAAAAAAgFdAAAAAAABAU0AAAAAAAABXQAAAAAAAQFRAAAAAAAAATUAAAAAAAOBWQAAAAAAAAFlAAAAAAABAVUAAAAAAAIBSQAAAAAAA4FNAAAAAAACgUUAAAAAAAABSQAAAAAAAQFVAAAAAAAAAUEAAAAAAAEBTQAAAAAAAgFJAAAAAAABAUEAAAAAAAEBUQAAAAAAAQFRA\",\"dtype\":\"float64\",\"order\":\"little\",\"shape\":[102]}},\"selected\":{\"id\":\"1308\"},\"selection_policy\":{\"id\":\"1307\"}},\"id\":\"1241\",\"type\":\"ColumnDataSource\"},{\"attributes\":{},\"id\":\"1302\",\"type\":\"BasicTickFormatter\"},{\"attributes\":{\"args\":{\"colorby_selector\":{\"id\":\"1240\"},\"render_source\":{\"id\":\"1241\"},\"source\":{\"id\":\"1242\"},\"x_selector\":{\"id\":\"1238\"},\"xaxis\":[{\"id\":\"1252\"}],\"y_selector\":{\"id\":\"1239\"},\"yaxis\":[{\"id\":\"1256\"}]},\"code\":\"\\n// Extract what we want to color by from selector\\nlet colorby = colorby_selector.value;\\n\\n// View of the colors for convenience\\nlet colors = render_source.data['color'];\\n\\n// Convenient to have the number of data points\\nlet n = colors.length;\\n\\n// New data\\nrender_source.data['x'] = source.data[x_selector.value];\\nrender_source.data['y'] = source.data[y_selector.value];\\n\\n// Update colors\\nif (colorby === 'none') {\\n for (let i = 0; i < n; i++) {\\n colors[i] = '#1f77b3';\\n }\\n}\\nelse if (colorby === 'gender') {\\n for (let i = 0; i < n; i++) {\\n if (source.data['gender'][i] === 'f') {\\n colors[i] = '#1f77b3';\\n }\\n else {\\n colors[i] = '#ff7e0e';\\n }\\n }\\n}\\nelse if (colorby === 'insomnia') {\\n for (let i = 0; i < n; i++) {\\n if (source.data['insomnia'][i]) {\\n colors[i] = '#1f77b3';\\n }\\n else {\\n colors[i] = '#ff7e0e';\\n }\\n }\\n}\\n\\n// Update axis labels to reflect what was selected\\nxaxis[0].axis_label = x_selector.value;\\nyaxis[0].axis_label = y_selector.value;\\n\\nrender_source.change.emit();\\n\"},\"id\":\"1282\",\"type\":\"CustomJS\"},{\"attributes\":{\"fill_alpha\":{\"value\":0.2},\"fill_color\":{\"field\":\"color\"},\"hatch_alpha\":{\"value\":0.2},\"line_alpha\":{\"value\":0.2},\"line_color\":{\"field\":\"color\"},\"x\":{\"field\":\"x\"},\"y\":{\"field\":\"y\"}},\"id\":\"1277\",\"type\":\"Circle\"},{\"attributes\":{},\"id\":\"1263\",\"type\":\"SaveTool\"},{\"attributes\":{},\"id\":\"1310\",\"type\":\"UnionRenderers\"},{\"attributes\":{},\"id\":\"1261\",\"type\":\"WheelZoomTool\"},{\"attributes\":{\"overlay\":{\"id\":\"1266\"}},\"id\":\"1262\",\"type\":\"BoxZoomTool\"},{\"attributes\":{\"args\":{\"colorby_selector\":{\"id\":\"1240\"},\"render_source\":{\"id\":\"1241\"},\"source\":{\"id\":\"1242\"},\"x_selector\":{\"id\":\"1238\"},\"xaxis\":[{\"id\":\"1252\"}],\"y_selector\":{\"id\":\"1239\"},\"yaxis\":[{\"id\":\"1256\"}]},\"code\":\"\\n// Extract what we want to color by from selector\\nlet colorby = colorby_selector.value;\\n\\n// View of the colors for convenience\\nlet colors = render_source.data['color'];\\n\\n// Convenient to have the number of data points\\nlet n = colors.length;\\n\\n// New data\\nrender_source.data['x'] = source.data[x_selector.value];\\nrender_source.data['y'] = source.data[y_selector.value];\\n\\n// Update colors\\nif (colorby === 'none') {\\n for (let i = 0; i < n; i++) {\\n colors[i] = '#1f77b3';\\n }\\n}\\nelse if (colorby === 'gender') {\\n for (let i = 0; i < n; i++) {\\n if (source.data['gender'][i] === 'f') {\\n colors[i] = '#1f77b3';\\n }\\n else {\\n colors[i] = '#ff7e0e';\\n }\\n }\\n}\\nelse if (colorby === 'insomnia') {\\n for (let i = 0; i < n; i++) {\\n if (source.data['insomnia'][i]) {\\n colors[i] = '#1f77b3';\\n }\\n else {\\n colors[i] = '#ff7e0e';\\n }\\n }\\n}\\n\\n// Update axis labels to reflect what was selected\\nxaxis[0].axis_label = x_selector.value;\\nyaxis[0].axis_label = y_selector.value;\\n\\nrender_source.change.emit();\\n\"},\"id\":\"1280\",\"type\":\"CustomJS\"},{\"attributes\":{},\"id\":\"1257\",\"type\":\"BasicTicker\"},{\"attributes\":{},\"id\":\"1308\",\"type\":\"Selection\"},{\"attributes\":{},\"id\":\"1311\",\"type\":\"Selection\"},{\"attributes\":{\"coordinates\":null,\"data_source\":{\"id\":\"1241\"},\"glyph\":{\"id\":\"1275\"},\"group\":null,\"hover_glyph\":null,\"muted_glyph\":{\"id\":\"1277\"},\"nonselection_glyph\":{\"id\":\"1276\"},\"view\":{\"id\":\"1279\"}},\"id\":\"1278\",\"type\":\"GlyphRenderer\"},{\"attributes\":{},\"id\":\"1265\",\"type\":\"HelpTool\"},{\"attributes\":{\"below\":[{\"id\":\"1252\"}],\"center\":[{\"id\":\"1255\"},{\"id\":\"1259\"}],\"frame_height\":250,\"frame_width\":250,\"left\":[{\"id\":\"1256\"}],\"renderers\":[{\"id\":\"1278\"}],\"title\":{\"id\":\"1299\"},\"toolbar\":{\"id\":\"1267\"},\"x_range\":{\"id\":\"1244\"},\"x_scale\":{\"id\":\"1248\"},\"y_range\":{\"id\":\"1246\"},\"y_scale\":{\"id\":\"1250\"}},\"id\":\"1243\",\"subtype\":\"Figure\",\"type\":\"Plot\"},{\"attributes\":{},\"id\":\"1260\",\"type\":\"PanTool\"},{\"attributes\":{},\"id\":\"1250\",\"type\":\"LinearScale\"},{\"attributes\":{\"fill_alpha\":{\"value\":0.1},\"fill_color\":{\"field\":\"color\"},\"hatch_alpha\":{\"value\":0.1},\"line_alpha\":{\"value\":0.1},\"line_color\":{\"field\":\"color\"},\"x\":{\"field\":\"x\"},\"y\":{\"field\":\"y\"}},\"id\":\"1276\",\"type\":\"Circle\"},{\"attributes\":{\"axis_label\":\"percent correct\",\"coordinates\":null,\"formatter\":{\"id\":\"1305\"},\"group\":null,\"major_label_policy\":{\"id\":\"1306\"},\"ticker\":{\"id\":\"1253\"}},\"id\":\"1252\",\"type\":\"LinearAxis\"},{\"attributes\":{},\"id\":\"1303\",\"type\":\"AllLabels\"},{\"attributes\":{\"js_property_callbacks\":{\"change:value\":[{\"id\":\"1281\"}]},\"options\":[\"age\",\"correct hit percentage\",\"correct reject percentage\",\"percent correct\",\"confidence when correct hit\",\"confidence when incorrect hit\",\"confidence when correct reject\",\"confidence when incorrect reject\",\"confidence when correct\",\"confidence when incorrect\",\"sci\",\"psqi\",\"ess\"],\"title\":\"x\",\"value\":\"percent correct\",\"width\":200},\"id\":\"1238\",\"type\":\"Select\"},{\"attributes\":{\"js_property_callbacks\":{\"change:value\":[{\"id\":\"1282\"}]},\"options\":[\"age\",\"correct hit percentage\",\"correct reject percentage\",\"percent correct\",\"confidence when correct hit\",\"confidence when incorrect hit\",\"confidence when correct reject\",\"confidence when incorrect reject\",\"confidence when correct\",\"confidence when incorrect\",\"sci\",\"psqi\",\"ess\"],\"title\":\"y\",\"value\":\"confidence when correct\",\"width\":200},\"id\":\"1239\",\"type\":\"Select\"},{\"attributes\":{\"height\":15},\"id\":\"1285\",\"type\":\"Spacer\"},{\"attributes\":{},\"id\":\"1305\",\"type\":\"BasicTickFormatter\"},{\"attributes\":{\"tools\":[{\"id\":\"1260\"},{\"id\":\"1261\"},{\"id\":\"1262\"},{\"id\":\"1263\"},{\"id\":\"1264\"},{\"id\":\"1265\"}]},\"id\":\"1267\",\"type\":\"Toolbar\"},{\"attributes\":{\"js_property_callbacks\":{\"change:value\":[{\"id\":\"1280\"}]},\"options\":[\"none\",\"gender\",\"insomnia\"],\"title\":\"color by\",\"value\":\"none\",\"width\":200},\"id\":\"1240\",\"type\":\"Select\"},{\"attributes\":{},\"id\":\"1307\",\"type\":\"UnionRenderers\"},{\"attributes\":{\"fill_color\":{\"field\":\"color\"},\"line_color\":{\"field\":\"color\"},\"x\":{\"field\":\"x\"},\"y\":{\"field\":\"y\"}},\"id\":\"1275\",\"type\":\"Circle\"},{\"attributes\":{},\"id\":\"1253\",\"type\":\"BasicTicker\"},{\"attributes\":{},\"id\":\"1246\",\"type\":\"DataRange1d\"},{\"attributes\":{\"width\":15},\"id\":\"1283\",\"type\":\"Spacer\"},{\"attributes\":{\"source\":{\"id\":\"1241\"}},\"id\":\"1279\",\"type\":\"CDSView\"},{\"attributes\":{},\"id\":\"1248\",\"type\":\"LinearScale\"},{\"attributes\":{},\"id\":\"1306\",\"type\":\"AllLabels\"},{\"attributes\":{},\"id\":\"1264\",\"type\":\"ResetTool\"},{\"attributes\":{\"args\":{\"colorby_selector\":{\"id\":\"1240\"},\"render_source\":{\"id\":\"1241\"},\"source\":{\"id\":\"1242\"},\"x_selector\":{\"id\":\"1238\"},\"xaxis\":[{\"id\":\"1252\"}],\"y_selector\":{\"id\":\"1239\"},\"yaxis\":[{\"id\":\"1256\"}]},\"code\":\"\\n// Extract what we want to color by from selector\\nlet colorby = colorby_selector.value;\\n\\n// View of the colors for convenience\\nlet colors = render_source.data['color'];\\n\\n// Convenient to have the number of data points\\nlet n = colors.length;\\n\\n// New data\\nrender_source.data['x'] = source.data[x_selector.value];\\nrender_source.data['y'] = source.data[y_selector.value];\\n\\n// Update colors\\nif (colorby === 'none') {\\n for (let i = 0; i < n; i++) {\\n colors[i] = '#1f77b3';\\n }\\n}\\nelse if (colorby === 'gender') {\\n for (let i = 0; i < n; i++) {\\n if (source.data['gender'][i] === 'f') {\\n colors[i] = '#1f77b3';\\n }\\n else {\\n colors[i] = '#ff7e0e';\\n }\\n }\\n}\\nelse if (colorby === 'insomnia') {\\n for (let i = 0; i < n; i++) {\\n if (source.data['insomnia'][i]) {\\n colors[i] = '#1f77b3';\\n }\\n else {\\n colors[i] = '#ff7e0e';\\n }\\n }\\n}\\n\\n// Update axis labels to reflect what was selected\\nxaxis[0].axis_label = x_selector.value;\\nyaxis[0].axis_label = y_selector.value;\\n\\nrender_source.change.emit();\\n\"},\"id\":\"1281\",\"type\":\"CustomJS\"},{\"attributes\":{\"children\":[{\"id\":\"1238\"},{\"id\":\"1284\"},{\"id\":\"1239\"},{\"id\":\"1285\"},{\"id\":\"1240\"}]},\"id\":\"1286\",\"type\":\"Column\"},{\"attributes\":{\"axis_label\":\"confidence when correct\",\"coordinates\":null,\"formatter\":{\"id\":\"1302\"},\"group\":null,\"major_label_policy\":{\"id\":\"1303\"},\"ticker\":{\"id\":\"1257\"}},\"id\":\"1256\",\"type\":\"LinearAxis\"},{\"attributes\":{},\"id\":\"1244\",\"type\":\"DataRange1d\"},{\"attributes\":{\"coordinates\":null,\"group\":null},\"id\":\"1299\",\"type\":\"Title\"},{\"attributes\":{\"axis\":{\"id\":\"1256\"},\"coordinates\":null,\"dimension\":1,\"group\":null,\"ticker\":null},\"id\":\"1259\",\"type\":\"Grid\"},{\"attributes\":{\"axis\":{\"id\":\"1252\"},\"coordinates\":null,\"group\":null,\"ticker\":null},\"id\":\"1255\",\"type\":\"Grid\"},{\"attributes\":{\"data\":{\"age\":[39,42,31,35,74,61,32,62,33,53,41,36,40,24,32,40,61,42,31,28,26,45,28,44,28,42,45,16,21,18,28,38,17,25,22,41,53,43,23,19,45,43,35,24,64,36,35,43,44,29,22,46,35,53,29,31,21,42,23,54,24,21,21,43,50,53,16,67,36,34,42,46,69,31,44,25,45,47,33,18,74,21,45,37,41,41,34,39,18,31,26,66,62,22,41,46,56,23,70,24,40,33],\"confidence when correct\":{\"__ndarray__\":\"AAAAAABAV0AAAAAAAMBSQAAAAAAAQFZAAAAAAAAAVkAAAAAAAEBQQAAAAAAAIFBAAAAAAACAUEAAAAAAAABPQAAAAAAAAFFAAAAAAADAUUAAAAAAAIBUQAAAAAAAAFNAAAAAAADgU0AAAAAAAIBLQAAAAAAAQFVAAAAAAACAUUAAAAAAAEBLQAAAAAAAIFZAAAAAAADgVUAAAAAAAABZQAAAAAAAQFNAAAAAAAAAWUAAAAAAAABUQAAAAAAAYFFAAAAAAABAVEAA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QQAAAAAAAAPh/AAAAAAAATEAAAAAAAIBOQAAAAAAAwFJAAAAAAABASkAAAAAAAKBQQAAAAAAAYFVAAAAAAABAVEAAAAAAAIBCQAAAAAAAADtA\",\"dtype\":\"float64\",\"order\":\"little\",\"shape\":[102]},\"confidence when incorrect reject\":{\"__ndarray__\":\"AAAAAADgVEAAAAAAAABJQAAAAAAAQFRAAAAAAAAAVEAAAAAAAIBIQAAAAAAAIFJAAAAAAABAUEAAAAAAAGBUQAAAAAAAAPh/AAAAAABAUEAAAAAAAEBRQAAAAAAAAPh/AAAAAABATUAAAAAAAABRQAAAAAAAgFVAAAAAAAAA+H8AAAAAAEBSQAAAAAAAwEVAAAAAAAAATkAAAAAAAABZQAAAAAAA4FBAAAAAAAAAWUAAAAAAAABOQAAAAAAAQFNAAAAAAAAAS0AAAAAAAIBIQAAAAAAAwFJAAAAAAACASkAAAAAAAABJQAAAAAAAAPh/AAAAAACATkAAAAAAAAA1QAAAAAAAADtAAAAAAAAA+H8AAAAAAEBQQAAAAAAAQEpAAAAAAACASEAAAAAAAABCQAAAAAAAoFBAAAAAAABASUAAAAAAAABLQAAAAAAAgE1AAAAAAAAA+H8AAAAAAAD4fwAAAAAAADhAAAAAAADAT0AAAAAAAMBEQAAAAAAAgEZAAAAAAABARUAAAAAAAIBKQAAAAAAAAFRAAAAAAADAVkAAAAAAAABAQAAAAAAAoFNAAAAAAACARUAAAAAAAABCQAAAAAAAAD1AAAAAAAAAQkAAAAAAAABEQAAAAAAAQFFAAAAAAABAUkAAAAAAAABRQAAAAAAAgFFAAAAAAABAUEAAAAAAAEBQQAAAAAAAgE5AAAAAAAAAREAAAAAAAABOQAAAAAAAAEpAAAAAAADASkAAAAAAAAD4fwAAAAAAgE9AAAAAAACgUUAAAAAAAABEQAAAAAAAwFVAAAAAAAAA+H8AAAAAAEBRQAAAAAAAwFRAAAAAAABAUEAAAAAAAIBMQAAAAAAAQElAAAAAAADAVEAAAAAAAAAxQAAAAAAAwFRAAAAAAACAREAAAAAAAIBSQAAAAAAAAE1AAAAAAAAASUAAAAAAAEBWQAAAAAAAAElAAAAAAACAVEAAAAAAAIBMQAAAAAAAgFRAAAAAAACAT0AAAAAAAIBMQAAAAAAAAFRAAAAAAABgUEAAAAAAAGBTQAAAAAAAAFRAAAAAAACATkAAAAAAAABKQAAAAAAAoFRA\",\"dtype\":\"float64\",\"order\":\"little\",\"shape\":[102]},\"correct hit percentage\":[65,90,90,100,60,80,90,45,80,100,70,90,95,85,75,40,100,70,100,100,60,100,100,65,100,80,80,70,70,90,95,90,90,100,80,90,95,95,90,55,100,65,90,55,75,100,70,90,95,95,70,80,50,65,100,85,85,90,90,90,85,85,90,95,70,95,85,95,90,90,100,80,95,100,90,100,70,90,85,80,85,40,80,90,90,80,90,75,85,100,95,60,100,85,35,95,70,70,90,70,75,85],\"correct reject percentage\":[80,90,95,75,65,20,75,90,100,50,55,100,65,75,55,100,40,90,70,50,80,95,75,25,40,65,90,80,65,100,80,95,90,100,60,80,60,90,80,60,85,65,100,100,85,80,90,85,90,55,65,75,95,80,70,90,90,90,85,70,95,75,80,75,85,75,85,75,65,90,100,90,80,95,95,100,50,100,70,75,80,40,95,80,85,75,35,70,85,85,75,85,80,95,75,80,50,85,85,80,65,40],\"ess\":[2,7,3,20,12,2,3,9,10,7,19,0,8,4,7,14,12,10,11,12,1,6,4,6,2,5,1,3,4,5,12,4,4,11,6,3,11,10,12,6,13,12,5,10,4,4,6,3,0,12,6,5,9,7,6,10,18,11,8,16,7,9,11,4,7,4,11,12,3,3,4,11,1,4,2,9,1,2,12,6,5,5,4,9,3,8,6,10,21,5,5,9,1,8,11,5,7,10,7,15,7,7],\"gender\":[\"f\",\"m\",\"f\",\"f\",\"f\",\"f\",\"m\",\"m\",\"f\",\"f\",\"f\",\"f\",\"f\",\"f\",\"f\",\"f\",\"f\",\"f\",\"m\",\"m\",\"f\",\"m\",\"f\",\"f\",\"f\",\"f\",\"f\",\"f\",\"f\",\"f\",\"f\",\"f\",\"m\",\"f\",\"f\",\"m\",\"m\",\"m\",\"f\",\"m\",\"f\",\"f\",\"m\",\"m\",\"f\",\"f\",\"m\",\"f\",\"m\",\"f\",\"m\",\"f\",\"f\",\"m\",\"m\",\"f\",\"f\",\"f\",\"f\",\"m\",\"f\",\"f\",\"f\",\"f\",\"m\",\"f\",\"f\",\"f\",\"m\",\"f\",\"f\",\"f\",\"f\",\"f\",\"f\",\"f\",\"f\",\"f\",\"f\",\"f\",\"f\",\"m\",\"f\",\"f\",\"m\",\"f\",\"f\",\"f\",\"f\",\"f\",\"m\",\"m\",\"m\",\"m\",\"f\",\"m\",\"f\",\"f\",\"f\",\"f\",\"f\",\"f\"],\"index\":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101],\"insomnia\":[true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false],\"participant number\":[8,16,18,22,27,28,30,33,34,35,38,41,46,49,55,71,76,77,78,80,89,90,93,100,101,1,2,3,4,5,6,7,9,10,11,12,13,14,15,17,19,20,21,23,24,25,26,29,31,32,36,37,39,40,42,43,44,45,48,50,51,52,53,54,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,72,73,74,75,79,81,82,83,84,85,86,87,88,91,92,94,95,96,97,98,99,102,103],\"percent correct\":{\"__ndarray__\":\"AAAAAAAgUkAAAAAAAIBW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E9A\",\"dtype\":\"float64\",\"order\":\"little\",\"shape\":[102]},\"psqi\":[13,11,9,8,9,14,9,9,12,8,5,7,12,13,13,11,4,10,6,7,8,9,7,15,7,1,5,1,5,7,7,3,3,10,4,5,2,2,2,5,2,3,3,4,9,5,2,1,4,8,2,2,6,3,1,5,7,3,6,6,1,6,4,4,3,5,2,7,4,0,5,1,1,4,1,8,4,2,7,4,1,7,4,5,6,4,2,3,4,3,1,5,2,1,1,3,6,8,8,2,4,5],\"sci\":[9,4,10,13,13,15,16,14,14,14,14,15,10,14,5,0,16,11,14,12,14,14,16,1,14,29,19,23,26,21,19,28,29,17,22,28,31,31,32,25,30,28,30,22,20,26,32,32,24,26,30,28,21,29,32,26,26,23,18,22,29,20,27,19,29,24,29,17,26,30,17,25,31,27,32,28,25,30,21,29,20,22,23,20,17,27,27,22,25,30,32,30,32,28,31,29,26,20,19,31,22,24]},\"selected\":{\"id\":\"1311\"},\"selection_policy\":{\"id\":\"1310\"}},\"id\":\"1242\",\"type\":\"ColumnDataSource\"}],\"root_ids\":[\"1287\"]},\"title\":\"Bokeh Application\",\"version\":\"2.4.2\"}};\n", " const render_items = [{\"docid\":\"62a9ed7b-63d4-441d-a11c-10a687ddd581\",\"root_ids\":[\"1287\"],\"roots\":{\"1287\":\"a320c0ef-8018-4f96-b92a-d7fdacaa385d\"}}];\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", " let attempts = 0;\n", " const 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": "1287" } }, "output_type": "display_data" } ], "source": [ "layout = bokeh.layouts.row(\n", " p,\n", " bokeh.layouts.Spacer(width=15),\n", " bokeh.layouts.column(\n", " x_selector,\n", " bokeh.layouts.Spacer(height=15),\n", " y_selector,\n", " bokeh.layouts.Spacer(height=15),\n", " colorby_selector,\n", " ),\n", ")\n", "\n", "bokeh.io.show(layout)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Beautiful! We can again save the result and have a stand-alone interactive HTML file." ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'/Users/bois/Dropbox/git/programming_bootcamp/2022/content/lessons/sleep_facial_recognition.html'" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bokeh.io.save(\n", " layout,\n", " \"sleep_facial_recognition.html\",\n", " resources=bokeh.resources.CDN,\n", " title=\"sleep facial recognition\",\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Conclusions\n", "\n", "I hope you can see that a little JavaScript goes a long way! But knowing just some basic JavaScript syntax, you can build totally sharable, browser-display-and-playable data displays." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Computing environment" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Python implementation: CPython\n", "Python version : 3.9.12\n", "IPython version : 8.3.0\n", "\n", "numpy : 1.21.5\n", "pandas : 1.4.2\n", "bokeh : 2.4.2\n", "jupyterlab: 3.3.2\n", "\n" ] } ], "source": [ "%load_ext watermark\n", "%watermark -v -p numpy,pandas,bokeh,jupyterlab" ] } ], "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.9.12" } }, "nbformat": 4, "nbformat_minor": 4 }