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

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

\\n\"+\n", " \"\\n\"+\n", " \"\\n\"+\n", " \"from bokeh.resources import INLINE\\n\"+\n", " \"output_notebook(resources=INLINE)\\n\"+\n", " \"\\n\"+\n", " \"
\"}};\n", "\n", " function display_loaded() {\n", " var el = document.getElementById(\"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", " const hashes = {\"https://cdn.bokeh.org/bokeh/release/bokeh-2.3.2.min.js\": \"XypntL49z55iwGVUW4qsEu83zKL3XEcz0MjuGOQ9SlaaQ68X/g+k1FcioZi7oQAc\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.3.2.min.js\": \"bEsM86IHGDTLCS0Zod8a8WM6Y4+lafAL/eSiyQcuPzinmWNgNO2/olUF0Z2Dkn5i\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.3.2.min.js\": \"TX0gSQTdXTTeScqxj6PVQxTiRW8DOoGVwinyi1D3kxv7wuxQ02XkOxv0xwiypcAH\"};\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", " if (url in hashes) {\n", " element.crossOrigin = \"anonymous\";\n", " element.integrity = \"sha384-\" + hashes[url];\n", " }\n", " console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n", " document.head.appendChild(element);\n", " }\n", " };\n", "\n", " function inject_raw_css(css) {\n", " const element = document.createElement(\"style\");\n", " element.appendChild(document.createTextNode(css));\n", " document.body.appendChild(element);\n", " }\n", "\n", " \n", " var js_urls = [\"https://cdn.bokeh.org/bokeh/release/bokeh-2.3.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.3.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.3.2.min.js\"];\n", " var css_urls = [];\n", " \n", "\n", " var inline_js = [\n", " function(Bokeh) {\n", " Bokeh.set_log_level(\"info\");\n", " },\n", " function(Bokeh) {\n", " \n", " \n", " }\n", " ];\n", "\n", " function run_inline_js() {\n", " \n", " if (root.Bokeh !== undefined || force === true) {\n", " \n", " for (var i = 0; i < inline_js.length; i++) {\n", " inline_js[i].call(root, root.Bokeh);\n", " }\n", " if (force === true) {\n", " display_loaded();\n", " }} else if (Date.now() < root._bokeh_timeout) {\n", " setTimeout(run_inline_js, 100);\n", " } else if (!root._bokeh_failed_load) {\n", " console.log(\"Bokeh: BokehJS failed to load within specified timeout.\");\n", " root._bokeh_failed_load = true;\n", " } else if (force !== true) {\n", " var cell = $(document.getElementById(\"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 var force = true;\n\n if (typeof root._bokeh_onload_callbacks === \"undefined\" || force === true) {\n root._bokeh_onload_callbacks = [];\n root._bokeh_is_loading = undefined;\n }\n\n \n\n \n if (typeof (root._bokeh_timeout) === \"undefined\" || force === true) {\n root._bokeh_timeout = Date.now() + 5000;\n root._bokeh_failed_load = false;\n }\n\n var NB_LOAD_WARNING = {'data': {'text/html':\n \"
\\n\"+\n \"

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

\\n\"+\n \"\\n\"+\n \"\\n\"+\n \"from bokeh.resources import INLINE\\n\"+\n \"output_notebook(resources=INLINE)\\n\"+\n \"\\n\"+\n \"
\"}};\n\n function display_loaded() {\n var el = document.getElementById(\"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 const hashes = {\"https://cdn.bokeh.org/bokeh/release/bokeh-2.3.2.min.js\": \"XypntL49z55iwGVUW4qsEu83zKL3XEcz0MjuGOQ9SlaaQ68X/g+k1FcioZi7oQAc\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.3.2.min.js\": \"bEsM86IHGDTLCS0Zod8a8WM6Y4+lafAL/eSiyQcuPzinmWNgNO2/olUF0Z2Dkn5i\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.3.2.min.js\": \"TX0gSQTdXTTeScqxj6PVQxTiRW8DOoGVwinyi1D3kxv7wuxQ02XkOxv0xwiypcAH\"};\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 if (url in hashes) {\n element.crossOrigin = \"anonymous\";\n element.integrity = \"sha384-\" + hashes[url];\n }\n console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n document.head.appendChild(element);\n }\n };\n\n function inject_raw_css(css) {\n const element = document.createElement(\"style\");\n element.appendChild(document.createTextNode(css));\n document.body.appendChild(element);\n }\n\n \n var js_urls = [\"https://cdn.bokeh.org/bokeh/release/bokeh-2.3.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.3.2.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.3.2.min.js\"];\n var css_urls = [];\n \n\n var inline_js = [\n function(Bokeh) {\n Bokeh.set_log_level(\"info\");\n },\n function(Bokeh) {\n \n \n }\n ];\n\n function run_inline_js() {\n \n if (root.Bokeh !== undefined || force === true) {\n \n for (var i = 0; i < inline_js.length; i++) {\n inline_js[i].call(root, root.Bokeh);\n }\n if (force === true) {\n display_loaded();\n }} else if (Date.now() < root._bokeh_timeout) {\n setTimeout(run_inline_js, 100);\n } else if (!root._bokeh_failed_load) {\n console.log(\"Bokeh: BokehJS failed to load within specified timeout.\");\n root._bokeh_failed_load = true;\n } else if (force !== true) {\n var cell = $(document.getElementById(\"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](l29_dashboards.ipynb), we can build remarkable interactivity in our data displays, allowing for low-effort exploration of data sets. Panel, with Bokeh output, allow us to write Python code that can update our displays as we adjust parameters or select variables. We can also serve up a notebook 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 `panel 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 just 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." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## JavaScript and Bokeh\n", "\n", "We have been using Bokeh for rendering out plots and dashboards. (Even though we used a Panel interface, the dashboards we have made are rendered with Bokeh.) 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 **callbacks**, which are functions that get executed to update information about the plot based on changes in the widgets (such as computing the values of a smooth curve, as we saw in our exploration of the theoretical model for fold change in gene expression, or selecting pieces of a Pandas data frame, as we saw in the dashboard for the facial recognition data), are in Python. This is what requires the Python interpreter to be running.\n", "\n", "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 little JavaScript goes a long way!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using ColumnDataSources\n", "\n", "Let's look at how we have been building plots with Bokeh so far. To make the plot, I'll first generate some random data." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "rg = np.random.default_rng()\n", "x = np.linspace(-3, 3, 50)\n", "y = rg.normal(x, 1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, I'll make a figure." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "p = bokeh.plotting.figure(\n", " frame_width=250,\n", " frame_height=250,\n", " x_axis_label='x',\n", " y_axis_label='y',\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Then, when it becomes time to populate glyphs, we specify arrays (or lists or columns of data frames) for `x` and `y`." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "\n", "
\n" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/javascript": [ "(function(root) {\n", " function embed_document(root) {\n", " \n", " var docs_json = {\"46159b71-e949-48ec-aa33-718f192ad63c\":{\"defs\":[],\"roots\":{\"references\":[{\"attributes\":{\"below\":[{\"id\":\"1012\"}],\"center\":[{\"id\":\"1015\"},{\"id\":\"1019\"}],\"frame_height\":250,\"frame_width\":250,\"left\":[{\"id\":\"1016\"}],\"renderers\":[{\"id\":\"1037\"}],\"title\":{\"id\":\"1040\"},\"toolbar\":{\"id\":\"1027\"},\"x_range\":{\"id\":\"1004\"},\"x_scale\":{\"id\":\"1008\"},\"y_range\":{\"id\":\"1006\"},\"y_scale\":{\"id\":\"1010\"}},\"id\":\"1003\",\"subtype\":\"Figure\",\"type\":\"Plot\"},{\"attributes\":{\"axis_label\":\"y\",\"formatter\":{\"id\":\"1044\"},\"major_label_policy\":{\"id\":\"1045\"},\"ticker\":{\"id\":\"1017\"}},\"id\":\"1016\",\"type\":\"LinearAxis\"},{\"attributes\":{\"axis\":{\"id\":\"1016\"},\"dimension\":1,\"ticker\":null},\"id\":\"1019\",\"type\":\"Grid\"},{\"attributes\":{},\"id\":\"1021\",\"type\":\"WheelZoomTool\"},{\"attributes\":{},\"id\":\"1042\",\"type\":\"AllLabels\"},{\"attributes\":{},\"id\":\"1017\",\"type\":\"BasicTicker\"},{\"attributes\":{\"active_multi\":null,\"tools\":[{\"id\":\"1020\"},{\"id\":\"1021\"},{\"id\":\"1022\"},{\"id\":\"1023\"},{\"id\":\"1024\"},{\"id\":\"1025\"}]},\"id\":\"1027\",\"type\":\"Toolbar\"},{\"attributes\":{},\"id\":\"1025\",\"type\":\"HelpTool\"},{\"attributes\":{},\"id\":\"1020\",\"type\":\"PanTool\"},{\"attributes\":{\"overlay\":{\"id\":\"1026\"}},\"id\":\"1022\",\"type\":\"BoxZoomTool\"},{\"attributes\":{},\"id\":\"1023\",\"type\":\"SaveTool\"},{\"attributes\":{},\"id\":\"1041\",\"type\":\"BasicTickFormatter\"},{\"attributes\":{},\"id\":\"1024\",\"type\":\"ResetTool\"},{\"attributes\":{\"source\":{\"id\":\"1034\"}},\"id\":\"1038\",\"type\":\"CDSView\"},{\"attributes\":{},\"id\":\"1047\",\"type\":\"UnionRenderers\"},{\"attributes\":{},\"id\":\"1048\",\"type\":\"Selection\"},{\"attributes\":{},\"id\":\"1040\",\"type\":\"Title\"},{\"attributes\":{},\"id\":\"1045\",\"type\":\"AllLabels\"},{\"attributes\":{},\"id\":\"1008\",\"type\":\"LinearScale\"},{\"attributes\":{\"bottom_units\":\"screen\",\"fill_alpha\":0.5,\"fill_color\":\"lightgrey\",\"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\":\"1026\",\"type\":\"BoxAnnotation\"},{\"attributes\":{},\"id\":\"1044\",\"type\":\"BasicTickFormatter\"},{\"attributes\":{\"axis_label\":\"x\",\"formatter\":{\"id\":\"1041\"},\"major_label_policy\":{\"id\":\"1042\"},\"ticker\":{\"id\":\"1013\"}},\"id\":\"1012\",\"type\":\"LinearAxis\"},{\"attributes\":{},\"id\":\"1006\",\"type\":\"DataRange1d\"},{\"attributes\":{\"axis\":{\"id\":\"1012\"},\"ticker\":null},\"id\":\"1015\",\"type\":\"Grid\"},{\"attributes\":{\"fill_color\":{\"value\":\"#1f77b4\"},\"line_color\":{\"value\":\"#1f77b4\"},\"x\":{\"field\":\"x\"},\"y\":{\"field\":\"y\"}},\"id\":\"1035\",\"type\":\"Circle\"},{\"attributes\":{},\"id\":\"1010\",\"type\":\"LinearScale\"},{\"attributes\":{\"data\":{\"x\":{\"__ndarray__\":\"AAAAAAAACMDByyl4OQUHwIOXU/ByCgbARGN9aKwPBcAFL6f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"dtype\":\"float64\",\"order\":\"little\",\"shape\":[50]}},\"selected\":{\"id\":\"1048\"},\"selection_policy\":{\"id\":\"1047\"}},\"id\":\"1034\",\"type\":\"ColumnDataSource\"},{\"attributes\":{\"fill_alpha\":{\"value\":0.1},\"fill_color\":{\"value\":\"#1f77b4\"},\"line_alpha\":{\"value\":0.1},\"line_color\":{\"value\":\"#1f77b4\"},\"x\":{\"field\":\"x\"},\"y\":{\"field\":\"y\"}},\"id\":\"1036\",\"type\":\"Circle\"},{\"attributes\":{},\"id\":\"1004\",\"type\":\"DataRange1d\"},{\"attributes\":{\"data_source\":{\"id\":\"1034\"},\"glyph\":{\"id\":\"1035\"},\"hover_glyph\":null,\"muted_glyph\":null,\"nonselection_glyph\":{\"id\":\"1036\"},\"view\":{\"id\":\"1038\"}},\"id\":\"1037\",\"type\":\"GlyphRenderer\"},{\"attributes\":{},\"id\":\"1013\",\"type\":\"BasicTicker\"}],\"root_ids\":[\"1003\"]},\"title\":\"Bokeh Application\",\"version\":\"2.3.2\"}};\n", " var render_items = [{\"docid\":\"46159b71-e949-48ec-aa33-718f192ad63c\",\"root_ids\":[\"1003\"],\"roots\":{\"1003\":\"6442e5f7-b735-4fd7-816e-7cccbe4ef132\"}}];\n", " root.Bokeh.embed.embed_items_notebook(docs_json, render_items);\n", "\n", " }\n", " if (root.Bokeh !== undefined) {\n", " embed_document(root);\n", " } else {\n", " var attempts = 0;\n", " var timer = setInterval(function(root) {\n", " if (root.Bokeh !== undefined) {\n", " clearInterval(timer);\n", " embed_document(root);\n", " } else {\n", " attempts++;\n", " if (attempts > 100) {\n", " clearInterval(timer);\n", " console.log(\"Bokeh: ERROR: Unable to run BokehJS code because BokehJS library is missing\");\n", " }\n", " }\n", " }, 10, root)\n", " }\n", "})(window);" ], "application/vnd.bokehjs_exec.v0+json": "" }, "metadata": { "application/vnd.bokehjs_exec.v0+json": { "id": "1003" } }, "output_type": "display_data" } ], "source": [ "p.circle(x, y)\n", "\n", "bokeh.io.show(p)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's now peak under the hood a bit. When we called `p.circle()`, we created a **renderer**, which populates the plot with glyphs. A plot has a list of renderers, which we can access with `p.renderes`." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[GlyphRenderer(id='1037', ...)]" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.renderers" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is a list of `GlyphRenderer` instances. Each `GlyphRenderer` has a `data_source` attribute, which contains the data that dictate where the glyphs are placed. Let's look at the `data_source` for the plot we have just made." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
ColumnDataSource(
id = '1034', …)
data = {'y': {'__ndarray__': 'f8OJFje9C8AdMPiM06T/v3WHRBzbmQzAsbn0809cCsAiGHkPWjUPwBr4L2qTCAHASEXjfTGiB8D3bPZQfwYEwPopvpRB2uG/Esoe7zb9A8COk/pLPhDyv3AIWNwVogfAG+oq6KKGAMCwAH//gz/6v2YLT42ywtm/LFsXUiFF9r+2ucc6Iz77v7s939kmD+y/1EPAqbHPxb8cvbh/jFXrv/75ZidgpMC/yqL7pKhH878lNW+wji70PxAkflUyXb8/6KDh2QxV6b9BOPLPwn7XP1Td/ReLEvy/ZhA+o8oA+z+uDN8XihrWP2icrsPE/Ni/QOk/kPfamr8VfQNr3bjnP8DJupbIT4K/wlfAqhIf7j/EaUmb0MHzP6dAwSNrePc/lIaagnhw3z/2cjhekpP6P+C9ypuzrKs/Yf5XSwcgA0AMLMe3Vo7uP/vXyDyKIPs/uRU4qs2rA0Bt4p0nkFT7P25ujx+fHQFAz+O31lCoAkCZwkkRvX8JQDMKGuviWAdAQJwm0dHOAEBj4U34PVMJQA==', 'shape': (50,), 'dtype': 'float64', 'order': 'little'}, 'x': {'__ndarray__': 'AAAAAAAACMDByyl4OQUHwIOXU/ByCgbARGN9aKwPBcAFL6fg5RQEwMb60FgfGgPAiMb60FgfAsBJkiRJkiQBwApeTsHLKQDAmFPwcgpe/r8a60NjfWj8v52Cl1Pwcvq/IBrrQ2N9+L+isT401of2vyVJkiRJkvS/p+DlFLyc8r8qeDkFL6fwv1gfGutDY+2/YE7Byyl46b9kfWisD43lv2isD431oeG/4LZt27Zt27/oFLycgpfTv+DlFLycgse/AIjG+tBYr7/Ah8b60FivP+DlFLycgsc/6BS8nIKX0z/Ytm3btm3bP2isD431oeE/ZH1orA+N5T9cTsHLKXjpP1gfGutDY+0/KHg5BS+n8D+o4OUUvJzyPyRJkiRJkvQ/oLE+NNaH9j8gGutDY334P5yCl1Pwcvo/GOtDY31o/D+YU/ByCl7+PwpeTsHLKQBASJIkSZIkAUCIxvrQWB8CQMb60FgfGgNABC+n4OUUBEBEY31orA8FQIKXU/ByCgZAwMspeDkFB0AAAAAAAAAIQA==', 'shape': (50,), 'dtype': 'float64', 'order': 'little'}},
js_event_callbacks = {},
js_property_callbacks = {},
name = None,
selected = Selection(id='1048', ...),
selection_policy = UnionRenderers(id='1047', ...),
subscribed_events = [],
syncable = True,
tags = [])
\n", "\n" ], "text/plain": [ "ColumnDataSource(id='1034', ...)" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.renderers[0].data_source" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is a `ColumnDataSource` instance. This Bokeh data type is at the heart of many of the plots you can make with Boken and is an object that we can interact directly with using JavaScript. Importantly, the `ColumnDataSource` has a `data` attribute that contains the data for the plot stored as a dictionary." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'x': array([-3. , -2.87755102, -2.75510204, -2.63265306, -2.51020408,\n", " -2.3877551 , -2.26530612, -2.14285714, -2.02040816, -1.89795918,\n", " -1.7755102 , -1.65306122, -1.53061224, -1.40816327, -1.28571429,\n", " -1.16326531, -1.04081633, -0.91836735, -0.79591837, -0.67346939,\n", " -0.55102041, -0.42857143, -0.30612245, -0.18367347, -0.06122449,\n", " 0.06122449, 0.18367347, 0.30612245, 0.42857143, 0.55102041,\n", " 0.67346939, 0.79591837, 0.91836735, 1.04081633, 1.16326531,\n", " 1.28571429, 1.40816327, 1.53061224, 1.65306122, 1.7755102 ,\n", " 1.89795918, 2.02040816, 2.14285714, 2.26530612, 2.3877551 ,\n", " 2.51020408, 2.63265306, 2.75510204, 2.87755102, 3. ]),\n", " 'y': array([-3.46739023, -1.97774081, -3.57512495, -3.29507437, -3.90105068,\n", " -2.12918742, -2.95419596, -2.50317252, -0.5578926 , -2.49863993,\n", " -1.12896566, -2.95414326, -2.06574041, -1.64050674, -0.40250839,\n", " -1.39187748, -1.70267032, -0.87684958, -0.17040082, -0.85419297,\n", " -0.13001635, -1.20499482, 1.26136655, 0.12251582, -0.7916321 ,\n", " 0.36711188, -1.75452718, 1.68769325, 0.34536984, -0.39042777,\n", " -0.02622592, 0.74131652, -0.00894124, 0.94129308, 1.23481808,\n", " 1.46689905, 0.49123967, 1.66102826, 0.05405198, 2.39063891,\n", " 0.95487533, 1.69544433, 2.45888837, 1.70814529, 2.13946366,\n", " 2.33218544, 3.18737234, 2.91840156, 2.10098613, 3.16564554])}" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.renderers[0].data_source.data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that we know how the data are represented under the hood in a Bokeh plot and have an understanding of how `ColumnDataSource`s work, we can instead create a plot directly using the `ColumnDataSource`. When a glyph method like `p.circle()` is called, if we use a `source` kwarg, we can specify a `ColumnDataSource` explicitly, giving us access to its contents. To instantiate a `ColumnDataSource`, we call `bokeh.models.ColumnDataSource` with a dictionary (or Pandas data frame) argument that will be used for the data." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "\n", "
\n" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/javascript": [ "(function(root) {\n", " function embed_document(root) {\n", " \n", " var docs_json = {\"db96e717-bd14-43e5-bc95-f6efe0098429\":{\"defs\":[],\"roots\":{\"references\":[{\"attributes\":{\"below\":[{\"id\":\"1118\"}],\"center\":[{\"id\":\"1121\"},{\"id\":\"1125\"}],\"frame_height\":250,\"frame_width\":250,\"left\":[{\"id\":\"1122\"}],\"renderers\":[{\"id\":\"1144\"}],\"title\":{\"id\":\"1158\"},\"toolbar\":{\"id\":\"1133\"},\"x_range\":{\"id\":\"1110\"},\"x_scale\":{\"id\":\"1114\"},\"y_range\":{\"id\":\"1112\"},\"y_scale\":{\"id\":\"1116\"}},\"id\":\"1109\",\"subtype\":\"Figure\",\"type\":\"Plot\"},{\"attributes\":{\"axis_label\":\"x\",\"formatter\":{\"id\":\"1159\"},\"major_label_policy\":{\"id\":\"1160\"},\"ticker\":{\"id\":\"1119\"}},\"id\":\"1118\",\"type\":\"LinearAxis\"},{\"attributes\":{},\"id\":\"1158\",\"type\":\"Title\"},{\"attributes\":{},\"id\":\"1165\",\"type\":\"UnionRenderers\"},{\"attributes\":{\"bottom_units\":\"screen\",\"fill_alpha\":0.5,\"fill_color\":\"lightgrey\",\"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\":\"1132\",\"type\":\"BoxAnnotation\"},{\"attributes\":{},\"id\":\"1166\",\"type\":\"Selection\"},{\"attributes\":{\"data\":{\"x\":{\"__ndarray__\":\"AAAAAAAACMDByyl4OQUHwIOXU/ByCgbARGN9aKwPBcAFL6fg5RQEwMb60FgfGgPAiMb60FgfAsBJkiRJkiQBwApeTsHLKQDAmFPwcgpe/r8a60NjfWj8v52Cl1Pwcvq/IBrrQ2N9+L+isT401of2vyVJkiRJkvS/p+DlFLyc8r8qeDkFL6fwv1gfGutDY+2/YE7Byyl46b9kfWisD43lv2isD431oeG/4LZt27Zt27/oFLycgpfTv+DlFLycgse/AIjG+tBYr7/Ah8b60FivP+DlFLycgsc/6BS8nIKX0z/Ytm3btm3bP2isD431oeE/ZH1orA+N5T9cTsHLKXjpP1gfGutDY+0/KHg5BS+n8D+o4OUUvJzyPyRJkiRJkvQ/oLE+NNaH9j8gGutDY334P5yCl1Pwcvo/GOtDY31o/D+YU/ByCl7+PwpeTsHLKQBASJIkSZIkAUCIxvrQWB8CQMb60FgfGgNABC+n4OUUBEBEY31orA8FQIKXU/ByCgZAwMspeDkFB0AAAAAAAAAIQA==\",\"dtype\":\"float64\",\"order\":\"little\",\"shape\":[50]},\"y\":{\"__ndarray__\":\"f8OJFje9C8AdMPiM06T/v3WHRBzbmQzAsbn0809cCsAiGHkPWjUPwBr4L2qTCAHASEXjfTGiB8D3bPZQfwYEwPopvpRB2uG/Esoe7zb9A8COk/pLPhDyv3AIWNwVogfAG+oq6KKGAMCwAH//gz/6v2YLT42ywtm/LFsXUiFF9r+2ucc6Iz77v7s939kmD+y/1EPAqbHPxb8cvbh/jFXrv/75ZidgpMC/yqL7pKhH878lNW+wji70PxAkflUyXb8/6KDh2QxV6b9BOPLPwn7XP1Td/ReLEvy/ZhA+o8oA+z+uDN8XihrWP2icrsPE/Ni/QOk/kPfamr8VfQNr3bjnP8DJupbIT4K/wlfAqhIf7j/EaUmb0MHzP6dAwSNrePc/lIaagnhw3z/2cjhekpP6P+C9ypuzrKs/Yf5XSwcgA0AMLMe3Vo7uP/vXyDyKIPs/uRU4qs2rA0Bt4p0nkFT7P25ujx+fHQFAz+O31lCoAkCZwkkRvX8JQDMKGuviWAdAQJwm0dHOAEBj4U34PVMJQA==\",\"dtype\":\"float64\",\"order\":\"little\",\"shape\":[50]}},\"selected\":{\"id\":\"1166\"},\"selection_policy\":{\"id\":\"1165\"}},\"id\":\"1140\",\"type\":\"ColumnDataSource\"},{\"attributes\":{\"fill_color\":{\"value\":\"#1f77b4\"},\"line_color\":{\"value\":\"#1f77b4\"},\"x\":{\"field\":\"x\"},\"y\":{\"field\":\"y\"}},\"id\":\"1142\",\"type\":\"Circle\"},{\"attributes\":{},\"id\":\"1110\",\"type\":\"DataRange1d\"},{\"attributes\":{},\"id\":\"1159\",\"type\":\"BasicTickFormatter\"},{\"attributes\":{},\"id\":\"1114\",\"type\":\"LinearScale\"},{\"attributes\":{},\"id\":\"1160\",\"type\":\"AllLabels\"},{\"attributes\":{},\"id\":\"1112\",\"type\":\"DataRange1d\"},{\"attributes\":{},\"id\":\"1116\",\"type\":\"LinearScale\"},{\"attributes\":{},\"id\":\"1119\",\"type\":\"BasicTicker\"},{\"attributes\":{\"axis\":{\"id\":\"1118\"},\"ticker\":null},\"id\":\"1121\",\"type\":\"Grid\"},{\"attributes\":{},\"id\":\"1127\",\"type\":\"WheelZoomTool\"},{\"attributes\":{\"axis_label\":\"y\",\"formatter\":{\"id\":\"1162\"},\"major_label_policy\":{\"id\":\"1163\"},\"ticker\":{\"id\":\"1123\"}},\"id\":\"1122\",\"type\":\"LinearAxis\"},{\"attributes\":{\"axis\":{\"id\":\"1122\"},\"dimension\":1,\"ticker\":null},\"id\":\"1125\",\"type\":\"Grid\"},{\"attributes\":{},\"id\":\"1162\",\"type\":\"BasicTickFormatter\"},{\"attributes\":{},\"id\":\"1123\",\"type\":\"BasicTicker\"},{\"attributes\":{\"active_multi\":null,\"tools\":[{\"id\":\"1126\"},{\"id\":\"1127\"},{\"id\":\"1128\"},{\"id\":\"1129\"},{\"id\":\"1130\"},{\"id\":\"1131\"}]},\"id\":\"1133\",\"type\":\"Toolbar\"},{\"attributes\":{},\"id\":\"1163\",\"type\":\"AllLabels\"},{\"attributes\":{},\"id\":\"1131\",\"type\":\"HelpTool\"},{\"attributes\":{\"fill_alpha\":{\"value\":0.1},\"fill_color\":{\"value\":\"#1f77b4\"},\"line_alpha\":{\"value\":0.1},\"line_color\":{\"value\":\"#1f77b4\"},\"x\":{\"field\":\"x\"},\"y\":{\"field\":\"y\"}},\"id\":\"1143\",\"type\":\"Circle\"},{\"attributes\":{},\"id\":\"1126\",\"type\":\"PanTool\"},{\"attributes\":{},\"id\":\"1129\",\"type\":\"SaveTool\"},{\"attributes\":{\"source\":{\"id\":\"1140\"}},\"id\":\"1145\",\"type\":\"CDSView\"},{\"attributes\":{\"overlay\":{\"id\":\"1132\"}},\"id\":\"1128\",\"type\":\"BoxZoomTool\"},{\"attributes\":{\"data_source\":{\"id\":\"1140\"},\"glyph\":{\"id\":\"1142\"},\"hover_glyph\":null,\"muted_glyph\":null,\"nonselection_glyph\":{\"id\":\"1143\"},\"view\":{\"id\":\"1145\"}},\"id\":\"1144\",\"type\":\"GlyphRenderer\"},{\"attributes\":{},\"id\":\"1130\",\"type\":\"ResetTool\"}],\"root_ids\":[\"1109\"]},\"title\":\"Bokeh Application\",\"version\":\"2.3.2\"}};\n", " var render_items = [{\"docid\":\"db96e717-bd14-43e5-bc95-f6efe0098429\",\"root_ids\":[\"1109\"],\"roots\":{\"1109\":\"e89e870a-8e02-4323-b77a-12ec0474f3c4\"}}];\n", " root.Bokeh.embed.embed_items_notebook(docs_json, render_items);\n", "\n", " }\n", " if (root.Bokeh !== undefined) {\n", " embed_document(root);\n", " } else {\n", " var attempts = 0;\n", " var timer = setInterval(function(root) {\n", " if (root.Bokeh !== undefined) {\n", " clearInterval(timer);\n", " embed_document(root);\n", " } else {\n", " attempts++;\n", " if (attempts > 100) {\n", " clearInterval(timer);\n", " console.log(\"Bokeh: ERROR: Unable to run BokehJS code because BokehJS library is missing\");\n", " }\n", " }\n", " }, 10, root)\n", " }\n", "})(window);" ], "application/vnd.bokehjs_exec.v0+json": "" }, "metadata": { "application/vnd.bokehjs_exec.v0+json": { "id": "1109" } }, "output_type": "display_data" } ], "source": [ "p = bokeh.plotting.figure(\n", " frame_width=250,\n", " frame_height=250,\n", " x_axis_label='x',\n", " y_axis_label='y',\n", ")\n", "\n", "# Make the ColumnDataSource\n", "cds = bokeh.models.ColumnDataSource(dict(x=x, y=y))\n", "\n", "# Populate glyphs\n", "p.circle(source=cds, x=\"x\", y=\"y\")\n", "\n", "bokeh.io.show(p)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that when we use the `source` kwarg, we specify the `x` and `y` values as keys of the dictionary containing the data.\n", "\n", "One of the beautiful properties about a `ColumnDataSource` is that we can update its data and the plot will also update." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "\n", "
\n" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/javascript": [ "(function(root) {\n", " function embed_document(root) {\n", " \n", " var docs_json = {\"ab92a6ed-0a97-46af-8263-eb4512af0200\":{\"defs\":[],\"roots\":{\"references\":[{\"attributes\":{\"below\":[{\"id\":\"1118\"}],\"center\":[{\"id\":\"1121\"},{\"id\":\"1125\"}],\"frame_height\":250,\"frame_width\":250,\"left\":[{\"id\":\"1122\"}],\"renderers\":[{\"id\":\"1144\"}],\"title\":{\"id\":\"1158\"},\"toolbar\":{\"id\":\"1133\"},\"x_range\":{\"id\":\"1110\"},\"x_scale\":{\"id\":\"1114\"},\"y_range\":{\"id\":\"1112\"},\"y_scale\":{\"id\":\"1116\"}},\"id\":\"1109\",\"subtype\":\"Figure\",\"type\":\"Plot\"},{\"attributes\":{\"axis_label\":\"x\",\"formatter\":{\"id\":\"1159\"},\"major_label_policy\":{\"id\":\"1160\"},\"ticker\":{\"id\":\"1119\"}},\"id\":\"1118\",\"type\":\"LinearAxis\"},{\"attributes\":{},\"id\":\"1158\",\"type\":\"Title\"},{\"attributes\":{},\"id\":\"1165\",\"type\":\"UnionRenderers\"},{\"attributes\":{\"bottom_units\":\"screen\",\"fill_alpha\":0.5,\"fill_color\":\"lightgrey\",\"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\":\"1132\",\"type\":\"BoxAnnotation\"},{\"attributes\":{},\"id\":\"1166\",\"type\":\"Selection\"},{\"attributes\":{\"data\":{\"x\":{\"__ndarray__\":\"AAAAAAAACMDByyl4OQUHwIOXU/ByCgbARGN9aKwPBcAFL6fg5RQEwMb60FgfGgPAiMb60FgfAsBJkiRJkiQBwApeTsHLKQDAmFPwcgpe/r8a60NjfWj8v52Cl1Pwcvq/IBrrQ2N9+L+isT401of2vyVJkiRJkvS/p+DlFLyc8r8qeDkFL6fwv1gfGutDY+2/YE7Byyl46b9kfWisD43lv2isD431oeG/4LZt27Zt27/oFLycgpfTv+DlFLycgse/AIjG+tBYr7/Ah8b60FivP+DlFLycgsc/6BS8nIKX0z/Ytm3btm3bP2isD431oeE/ZH1orA+N5T9cTsHLKXjpP1gfGutDY+0/KHg5BS+n8D+o4OUUvJzyPyRJkiRJkvQ/oLE+NNaH9j8gGutDY334P5yCl1Pwcvo/GOtDY31o/D+YU/ByCl7+PwpeTsHLKQBASJIkSZIkAUCIxvrQWB8CQMb60FgfGgNABC+n4OUUBEBEY31orA8FQIKXU/ByCgZAwMspeDkFB0AAAAAAAAAIQA==\",\"dtype\":\"float64\",\"order\":\"little\",\"shape\":[50]},\"y\":{\"__ndarray__\":\"KlZviM/J6z851y6jPaboPzO480Nc8+U/Gc8TtXKo4z8C1Iop17vhP2LuikjQI+A/Xq3EcGau3T9zBvWAlJvbP7rvPtciAdo/8syDkavT2D8xK4v/gwrYP00AWTvBn9c/3LFIVTSQ1z/uG8v6ZdvXP2ycVrGVg9g/PyXIPL2N2T+1/e5RlQHbP0sDfgiV6dw/75ToaeFS3z+O6qb6jibhPy50yh0F9eI/e5YXPmoe5T86hDFPg6znPxw0auh5qOo/22LA5ckZ7j9WYcfjcQLxP7PHbxPHNPM/gvcA/ZCg9T9D4QokaT74P6SwQmIiAvs/9OnFAmja/T+x7ZOwbVgAQN3HzdZptQFABRr/Imj1AkC9gI51SAkEQClCHFTS4gRAVD/LJxB2BUATJaqDjLoFQI1v4v8+rAVAQWLWiABMBUCaBPvBcp8EQKRfLdVesANAPDZnrqeLAkAt5caG/D8BQHLX0V7+uP8/dQ6rjxrf/D+2qTG7nQv6P+HbWxQ4U/c/ruuW6XTF9D8b5yEnzWzyPw==\",\"dtype\":\"float64\",\"order\":\"little\",\"shape\":[50]}},\"selected\":{\"id\":\"1166\"},\"selection_policy\":{\"id\":\"1165\"}},\"id\":\"1140\",\"type\":\"ColumnDataSource\"},{\"attributes\":{\"fill_color\":{\"value\":\"#1f77b4\"},\"line_color\":{\"value\":\"#1f77b4\"},\"x\":{\"field\":\"x\"},\"y\":{\"field\":\"y\"}},\"id\":\"1142\",\"type\":\"Circle\"},{\"attributes\":{},\"id\":\"1110\",\"type\":\"DataRange1d\"},{\"attributes\":{},\"id\":\"1159\",\"type\":\"BasicTickFormatter\"},{\"attributes\":{},\"id\":\"1114\",\"type\":\"LinearScale\"},{\"attributes\":{},\"id\":\"1160\",\"type\":\"AllLabels\"},{\"attributes\":{},\"id\":\"1112\",\"type\":\"DataRange1d\"},{\"attributes\":{},\"id\":\"1116\",\"type\":\"LinearScale\"},{\"attributes\":{},\"id\":\"1119\",\"type\":\"BasicTicker\"},{\"attributes\":{\"axis\":{\"id\":\"1118\"},\"ticker\":null},\"id\":\"1121\",\"type\":\"Grid\"},{\"attributes\":{},\"id\":\"1127\",\"type\":\"WheelZoomTool\"},{\"attributes\":{\"axis_label\":\"y\",\"formatter\":{\"id\":\"1162\"},\"major_label_policy\":{\"id\":\"1163\"},\"ticker\":{\"id\":\"1123\"}},\"id\":\"1122\",\"type\":\"LinearAxis\"},{\"attributes\":{\"axis\":{\"id\":\"1122\"},\"dimension\":1,\"ticker\":null},\"id\":\"1125\",\"type\":\"Grid\"},{\"attributes\":{},\"id\":\"1162\",\"type\":\"BasicTickFormatter\"},{\"attributes\":{},\"id\":\"1123\",\"type\":\"BasicTicker\"},{\"attributes\":{\"active_multi\":null,\"tools\":[{\"id\":\"1126\"},{\"id\":\"1127\"},{\"id\":\"1128\"},{\"id\":\"1129\"},{\"id\":\"1130\"},{\"id\":\"1131\"}]},\"id\":\"1133\",\"type\":\"Toolbar\"},{\"attributes\":{},\"id\":\"1163\",\"type\":\"AllLabels\"},{\"attributes\":{},\"id\":\"1131\",\"type\":\"HelpTool\"},{\"attributes\":{\"fill_alpha\":{\"value\":0.1},\"fill_color\":{\"value\":\"#1f77b4\"},\"line_alpha\":{\"value\":0.1},\"line_color\":{\"value\":\"#1f77b4\"},\"x\":{\"field\":\"x\"},\"y\":{\"field\":\"y\"}},\"id\":\"1143\",\"type\":\"Circle\"},{\"attributes\":{},\"id\":\"1126\",\"type\":\"PanTool\"},{\"attributes\":{},\"id\":\"1129\",\"type\":\"SaveTool\"},{\"attributes\":{\"source\":{\"id\":\"1140\"}},\"id\":\"1145\",\"type\":\"CDSView\"},{\"attributes\":{\"overlay\":{\"id\":\"1132\"}},\"id\":\"1128\",\"type\":\"BoxZoomTool\"},{\"attributes\":{\"data_source\":{\"id\":\"1140\"},\"glyph\":{\"id\":\"1142\"},\"hover_glyph\":null,\"muted_glyph\":null,\"nonselection_glyph\":{\"id\":\"1143\"},\"view\":{\"id\":\"1145\"}},\"id\":\"1144\",\"type\":\"GlyphRenderer\"},{\"attributes\":{},\"id\":\"1130\",\"type\":\"ResetTool\"}],\"root_ids\":[\"1109\"]},\"title\":\"Bokeh Application\",\"version\":\"2.3.2\"}};\n", " var render_items = [{\"docid\":\"ab92a6ed-0a97-46af-8263-eb4512af0200\",\"root_ids\":[\"1109\"],\"roots\":{\"1109\":\"72e50ea2-f8ea-4113-a4cd-9ac91e8387f5\"}}];\n", " root.Bokeh.embed.embed_items_notebook(docs_json, render_items);\n", "\n", " }\n", " if (root.Bokeh !== undefined) {\n", " embed_document(root);\n", " } else {\n", " var attempts = 0;\n", " var timer = setInterval(function(root) {\n", " if (root.Bokeh !== undefined) {\n", " clearInterval(timer);\n", " embed_document(root);\n", " } else {\n", " attempts++;\n", " if (attempts > 100) {\n", " clearInterval(timer);\n", " console.log(\"Bokeh: ERROR: Unable to run BokehJS code because BokehJS library is missing\");\n", " }\n", " }\n", " }, 10, root)\n", " }\n", "})(window);" ], "application/vnd.bokehjs_exec.v0+json": "" }, "metadata": { "application/vnd.bokehjs_exec.v0+json": { "id": "1109" } }, "output_type": "display_data" } ], "source": [ "# Change the y-data\n", "cds.data['y'] = np.exp(np.sin(x))\n", "\n", "# Reshow the plot\n", "bokeh.io.show(p)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `ColumnDataSource` can also be directly accessed in JavaScript callbacks. This is what will enable us to change the data in a plot in response to changes in widgets." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Example 1: Exploring the Normal pdf\n", "\n", "In our [lesson on dashboarding](l29_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 we used before to create the dashboard.\n", "\n", "```python\n", "opts = dict(show_grid=True, frame_height=200, frame_width=350, color=\"#1f77b3\")\n", "\n", "mu_slider = pn.widgets.FloatSlider(\n", " name=\"µ\", start=-5, end=5, step=0.1, value=0\n", ")\n", "sigma_slider = pn.widgets.FloatSlider(\n", " name=\"σ\", start=0.1, end=5, step=0.1, value=1\n", ")\n", "\n", "\n", "@pn.depends(mu_slider.param.value, sigma_slider.param.value)\n", "def plot_normal_pdf(mu=0, sigma=1):\n", " x = np.linspace(-10, 10, 200)\n", " y = scipy.stats.norm.pdf(x, loc=mu, scale=sigma)\n", "\n", " return hv.Curve(data=(x, y), kdims=[\"x\"], vdims=[\"f(x ; μ, σ)\"]).opts(\n", " **opts\n", " )\n", "\n", "\n", "widgets = pn.Column(\n", " pn.Spacer(height=30),\n", " mu_slider,\n", " pn.Spacer(height=15),\n", " sigma_slider,\n", " width=200,\n", ")\n", "\n", "pn.Row(plot_normal_pdf, pn.Spacer(width=15), widgets)\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 with Bokeh (not HoloViews)." ] }, { "cell_type": "code", "execution_count": 10, "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": [ "Notice that we are using sliders instantiated from Bokeh as opposed to Panel. That is, we use `bokeh.models.Slider()` instead of `pn.widgets.FloatSlider()`. (Note that the `name` kwarg for a Panel slider is `title` for a Bokeh slider; otherwise the syntax for their instantiation is the same.) I did this because when we render stand-alone HTML pages, there can be some problems with updating axis ranges when updated data in the stand-along HTML app. It's a bug in Panel that will likely be fixed soon.\n", "\n", "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": 11, "metadata": {}, "outputs": [], "source": [ "# Use a ColumnDataSource\n", "cds = bokeh.models.ColumnDataSource(dict(x=x, pdf=pdf))\n", "p.line(source=cds, x=\"x\", y=\"pdf\", line_width=2);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Laying out the sliders and plot is the same as before, except we will use Bokeh's native layout system instead of Panel's. They really only differ slightly." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "# Laying out the widgets is the same\n", "widgets = 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", "layout = bokeh.layouts.row(p, bokeh.layouts.Spacer(width=15), widgets)" ] }, { "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", " var 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", "var x = cds.data['x'];\n", "var pdf = cds.data['pdf'];\n", "\n", "// Pull the values off of the sliders\n", "var mu = mu_slider.value;\n", "var sigma = sigma_slider.value;\n", "\n", "// Loop through and update\n", "var xLen = x.length;\n", "for (var 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", "cds.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 `var` (or `let`, 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. 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. It is indexed just like you would index a dictionary in Python. For convenience in the above code, we create views into the `ColumnDataSource` using `var x = cds.data['x'];` and `var pdf = cds.data['pdf'];`.\n", "\n", "Next, we pull the values from the sliders. This is also done as in Python (except with the necessary `var`).\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 (var 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 `cds.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": 13, "metadata": {}, "outputs": [], "source": [ "# JavaScript code for the callback stored as a string\n", "jscode = \"\"\"\n", "function normalPDF(x, mu, sigma) {\n", " var 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", "var x = cds.data['x'];\n", "var pdf = cds.data['pdf'];\n", "\n", "// Pull the values off of the sliders\n", "var mu = mu_slider.value;\n", "var sigma = sigma_slider.value;\n", "\n", "// Loop through and update\n", "var xLen = x.length;\n", "for (var 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", "cds.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": 14, "metadata": {}, "outputs": [], "source": [ "args = dict(cds=cds, 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!" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "\n", "
\n" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/javascript": [ "(function(root) {\n", " function embed_document(root) {\n", " \n", " var docs_json = {\"aee9feb2-b3e1-47eb-bf00-fc32871cb734\":{\"defs\":[],\"roots\":{\"references\":[{\"attributes\":{\"children\":[{\"id\":\"1280\"},{\"id\":\"1320\"},{\"id\":\"1319\"}]},\"id\":\"1321\",\"type\":\"Row\"},{\"attributes\":{\"end\":5,\"js_property_callbacks\":{\"change:value\":[{\"id\":\"1322\"}]},\"start\":-5,\"step\":0.1,\"title\":\"\\u00b5\",\"value\":0},\"id\":\"1278\",\"type\":\"Slider\"},{\"attributes\":{\"below\":[{\"id\":\"1289\"}],\"center\":[{\"id\":\"1292\"},{\"id\":\"1296\"}],\"frame_height\":200,\"frame_width\":300,\"left\":[{\"id\":\"1293\"}],\"renderers\":[{\"id\":\"1315\"}],\"title\":{\"id\":\"1347\"},\"toolbar\":{\"id\":\"1304\"},\"x_range\":{\"id\":\"1281\"},\"x_scale\":{\"id\":\"1285\"},\"y_range\":{\"id\":\"1283\"},\"y_scale\":{\"id\":\"1287\"}},\"id\":\"1280\",\"subtype\":\"Figure\",\"type\":\"Plot\"},{\"attributes\":{\"source\":{\"id\":\"1311\"}},\"id\":\"1316\",\"type\":\"CDSView\"},{\"attributes\":{},\"id\":\"1354\",\"type\":\"UnionRenderers\"},{\"attributes\":{\"bottom_units\":\"screen\",\"fill_alpha\":0.5,\"fill_color\":\"lightgrey\",\"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\":\"1303\",\"type\":\"BoxAnnotation\"},{\"attributes\":{\"end\":10,\"start\":-10},\"id\":\"1281\",\"type\":\"Range1d\"},{\"attributes\":{},\"id\":\"1347\",\"type\":\"Title\"},{\"attributes\":{},\"id\":\"1287\",\"type\":\"LinearScale\"},{\"attributes\":{},\"id\":\"1297\",\"type\":\"PanTool\"},{\"attributes\":{\"axis_label\":\"x\",\"formatter\":{\"id\":\"1348\"},\"major_label_policy\":{\"id\":\"1349\"},\"ticker\":{\"id\":\"1290\"}},\"id\":\"1289\",\"type\":\"LinearAxis\"},{\"attributes\":{},\"id\":\"1283\",\"type\":\"DataRange1d\"},{\"attributes\":{},\"id\":\"1285\",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pXZCJAwkbvisyXIkDKhaibQcsiQNTEYay2/iJA3AMbvSsyI0DmQtTNoGUjQO6Bjd4VmSNA+MBG74rMI0AAAAAAAAAkQA==\",\"dtype\":\"float64\",\"order\":\"little\",\"shape\":[200]}},\"selected\":{\"id\":\"1355\"},\"selection_policy\":{\"id\":\"1354\"}},\"id\":\"1311\",\"type\":\"ColumnDataSource\"},{\"attributes\":{},\"id\":\"1355\",\"type\":\"Selection\"},{\"attributes\":{},\"id\":\"1290\",\"type\":\"BasicTicker\"},{\"attributes\":{\"axis\":{\"id\":\"1289\"},\"ticker\":null},\"id\":\"1292\",\"type\":\"Grid\"},{\"attributes\":{},\"id\":\"1298\",\"type\":\"WheelZoomTool\"},{\"attributes\":{\"axis_label\":\"f(x; \\u03bc, \\u03c3)\",\"formatter\":{\"id\":\"1351\"},\"major_label_policy\":{\"id\":\"1352\"},\"ticker\":{\"id\":\"1294\"}},\"id\":\"1293\",\"type\":\"LinearAxis\"},{\"attributes\":{\"line_alpha\":0.1,\"line_color\":\"#1f77b4\",\"line_width\":2,\"x\":{\"field\":\"x\"},\"y\":{\"field\":\"pdf\"}},\"id\":\"1314\",\"type\":\"Line\"},{\"attributes\":{\"axis\":{\"id\":\"1293\"},\"dimension\":1,\"ticker\":null},\"id\":\"1296\",\"type\":\"Grid\"},{\"attributes\":{},\"id\":\"1294\",\"type\":\"BasicTicker\"},{\"attributes\":{\"active_multi\":null,\"tools\":[{\"id\":\"1297\"},{\"id\":\"1298\"},{\"id\":\"1299\"},{\"id\":\"1300\"},{\"id\":\"1301\"},{\"id\":\"1302\"}]},\"id\":\"1304\",\"type\":\"Toolbar\"},{\"attributes\":{},\"id\":\"1302\",\"type\":\"HelpTool\"},{\"attributes\":{\"overlay\":{\"id\":\"1303\"}},\"id\":\"1299\",\"type\":\"BoxZoomTool\"},{\"attributes\":{\"data_source\":{\"id\":\"1311\"},\"glyph\":{\"id\":\"1313\"},\"hover_glyph\":null,\"muted_glyph\":null,\"nonselection_glyph\":{\"id\":\"1314\"},\"view\":{\"id\":\"1316\"}},\"id\":\"1315\",\"type\":\"GlyphRenderer\"},{\"attributes\":{},\"id\":\"1348\",\"type\":\"BasicTickFormatter\"},{\"attributes\":{},\"id\":\"1300\",\"type\":\"SaveTool\"},{\"attributes\":{},\"id\":\"1301\",\"type\":\"ResetTool\"},{\"attributes\":{\"children\":[{\"id\":\"1317\"},{\"id\":\"1278\"},{\"id\":\"1318\"},{\"id\":\"1279\"}],\"width\":200},\"id\":\"1319\",\"type\":\"Column\"},{\"attributes\":{},\"id\":\"1352\",\"type\":\"AllLabels\"},{\"attributes\":{},\"id\":\"1349\",\"type\":\"AllLabels\"},{\"attributes\":{\"args\":{\"cds\":{\"id\":\"1311\"},\"mu_slider\":{\"id\":\"1278\"},\"sigma_slider\":{\"id\":\"1279\"}},\"code\":\"\\nfunction normalPDF(x, mu, sigma) {\\n var 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\\nvar x = cds.data['x'];\\nvar pdf = cds.data['pdf'];\\n\\n// Pull the values off of the sliders\\nvar mu = mu_slider.value;\\nvar sigma = sigma_slider.value;\\n\\n// Loop through and update\\nvar xLen = x.length;\\nfor (var 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\\ncds.change.emit();\\n\"},\"id\":\"1322\",\"type\":\"CustomJS\"},{\"attributes\":{\"width\":15},\"id\":\"1320\",\"type\":\"Spacer\"},{\"attributes\":{\"line_color\":\"#1f77b4\",\"line_width\":2,\"x\":{\"field\":\"x\"},\"y\":{\"field\":\"pdf\"}},\"id\":\"1313\",\"type\":\"Line\"},{\"attributes\":{\"height\":30},\"id\":\"1317\",\"type\":\"Spacer\"},{\"attributes\":{},\"id\":\"1351\",\"type\":\"BasicTickFormatter\"},{\"attributes\":{\"height\":15},\"id\":\"1318\",\"type\":\"Spacer\"},{\"attributes\":{\"end\":5,\"js_property_callbacks\":{\"change:value\":[{\"id\":\"1323\"}]},\"start\":0.1,\"step\":0.1,\"title\":\"\\u03c3\",\"value\":1},\"id\":\"1279\",\"type\":\"Slider\"},{\"attributes\":{\"args\":{\"cds\":{\"id\":\"1311\"},\"mu_slider\":{\"id\":\"1278\"},\"sigma_slider\":{\"id\":\"1279\"}},\"code\":\"\\nfunction normalPDF(x, mu, sigma) {\\n var 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\\nvar x = cds.data['x'];\\nvar pdf = cds.data['pdf'];\\n\\n// Pull the values off of the sliders\\nvar mu = mu_slider.value;\\nvar sigma = sigma_slider.value;\\n\\n// Loop through and update\\nvar xLen = x.length;\\nfor (var 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\\ncds.change.emit();\\n\"},\"id\":\"1323\",\"type\":\"CustomJS\"}],\"root_ids\":[\"1321\"]},\"title\":\"Bokeh Application\",\"version\":\"2.3.2\"}};\n", " var render_items = [{\"docid\":\"aee9feb2-b3e1-47eb-bf00-fc32871cb734\",\"root_ids\":[\"1321\"],\"roots\":{\"1321\":\"dd6c5b13-17cd-42df-94f3-38218fd698a1\"}}];\n", " root.Bokeh.embed.embed_items_notebook(docs_json, render_items);\n", "\n", " }\n", " if (root.Bokeh !== undefined) {\n", " embed_document(root);\n", " } else {\n", " var attempts = 0;\n", " var timer = setInterval(function(root) {\n", " if (root.Bokeh !== undefined) {\n", " clearInterval(timer);\n", " embed_document(root);\n", " } else {\n", " attempts++;\n", " if (attempts > 100) {\n", " clearInterval(timer);\n", " console.log(\"Bokeh: ERROR: Unable to run BokehJS code because BokehJS library is missing\");\n", " }\n", " }\n", " }, 10, root)\n", " }\n", "})(window);" ], "application/vnd.bokehjs_exec.v0+json": "" }, "metadata": { "application/vnd.bokehjs_exec.v0+json": { "id": "1321" } }, "output_type": "display_data" } ], "source": [ "# Display the layout\n", "bokeh.io.show(layout)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is more or less the same about of work we did creating the dashboard with Panel except:\n", "\n", "1. We had to use Bokeh to build the sliders and layout (we didn't _have_ to, but it avoids some Panel bugs I've bumped in to recently)\n", "2. We used Bokeh instead of HoloViews to build the plot.\n", "3. We used a `ColumnDataSource` to do so.\n", "4. The callbacks were written in JavaScript and linked using `js_on_change()` instead of Panel decorators.\n", "\n", "That last item is the challenging one. 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": 16, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/Users/bois/opt/anaconda3/lib/python3.8/site-packages/bokeh/io/saving.py:126: UserWarning: save() called but no resources were supplied and output_file(...) was never called, defaulting to resources.CDN\n", " warn(\"save() called but no resources were supplied and output_file(...) was never called, defaulting to resources.CDN\")\n", "/Users/bois/opt/anaconda3/lib/python3.8/site-packages/bokeh/io/saving.py:139: UserWarning: save() called but no title was supplied and output_file(...) was never called, using default title 'Bokeh Plot'\n", " warn(\"save() called but no title was supplied and output_file(...) was never called, using default title 'Bokeh Plot'\")\n" ] }, { "data": { "text/plain": [ "'/Users/bois/Dropbox/git/programming_bootcamp/2021/content/lessons/normal_pdf_app.html'" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bokeh.io.save(layout, \"normal_pdf_app.html\")" ] }, { "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](l29_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. We set up a grid matrix of plots in that example. Here, I will demonstrate how to build a simpler dashboard, allowing for a single plot of one variable (e.g., percent correct facial discrimination) versus another (e.g. sleep score). The variables to be plotted can be selected, as can the categorical variable with which to color the glyphs. All interactions are with JavaScript callbacks, so 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": 17, "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": 17, "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." ] }, { "cell_type": "code", "execution_count": 18, "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`. In a dashboard like this, I find it is easier to set up a `ColumnDataSource` containing the columns that are used in rendering the plot (that is, only three columns, the x-values, the y-values, and the color-values). The color column is a column containing strings representing the colors. We'll start with a plot of confidence when correct versus percent correct with no additional coloring." ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "render_cds = 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 is using JavaScript." ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "cds = bokeh.models.ColumnDataSource(df)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we can make our figure!" ] }, { "cell_type": "code", "execution_count": 21, "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_cds, 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", "var colorby = colorby_selector.value;\n", "\n", "// View of the colors for convenience\n", "var colors = render_cds.data['color'];\n", "\n", "// Convenient to have the number of data points\n", "var n = colors.length;\n", "\n", "// Update rendered data from full data set\n", "render_cds.data['x'] = cds.data[x_selector.value];\n", "render_cds.data['y'] = cds.data[y_selector.value];\n", "\n", "// Update colors\n", "if (colorby === 'none') {\n", " for (var i = 0; i < n; i++) {\n", " colors[i] = '#1f77b3';\n", " }\n", "}\n", "else if (colorby === 'gender') {\n", " for (var i = 0; i < n; i++) {\n", " if (cds.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 (var i = 0; i < n; i++) {\n", " if (cds.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_cds.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", "Note that we have our JavaScript code, let's put it to use!" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "jscode = \"\"\"\n", "// Extract what we want to color by from selector\n", "var colorby = colorby_selector.value;\n", "\n", "// View of the colors for convenience\n", "var colors = render_cds.data['color'];\n", "\n", "// Convenient to have the number of data points\n", "var n = colors.length;\n", "\n", "// New data\n", "render_cds.data['x'] = cds.data[x_selector.value];\n", "render_cds.data['y'] = cds.data[y_selector.value];\n", "\n", "// Update colors\n", "if (colorby === 'none') {\n", " for (var i = 0; i < n; i++) {\n", " colors[i] = '#1f77b3';\n", " }\n", "}\n", "else if (colorby === 'gender') {\n", " for (var i = 0; i < n; i++) {\n", " if (cds.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 (var i = 0; i < n; i++) {\n", " if (cds.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_cds.change.emit();\n", "\"\"\"\n", "\n", "args = dict(\n", " render_cds=render_cds,\n", " cds=cds,\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": 23, "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": 24, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "\n", "
\n" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/javascript": [ "(function(root) {\n", " function embed_document(root) {\n", " \n", " var docs_json = {\"f8fbcf71-a69f-4b94-b088-617867eaab0b\":{\"defs\":[],\"roots\":{\"references\":[{\"attributes\":{\"children\":[{\"id\":\"1528\"},{\"id\":\"1567\"},{\"id\":\"1570\"}]},\"id\":\"1571\",\"type\":\"Row\"},{\"attributes\":{\"width\":15},\"id\":\"1567\",\"type\":\"Spacer\"},{\"attributes\":{},\"id\":\"1546\",\"type\":\"WheelZoomTool\"},{\"attributes\":{},\"id\":\"1535\",\"type\":\"LinearScale\"},{\"attributes\":{},\"id\":\"1616\",\"type\":\"UnionRenderers\"},{\"attributes\":{\"children\":[{\"id\":\"1523\"},{\"id\":\"1568\"},{\"id\":\"1524\"},{\"id\":\"1569\"},{\"id\":\"1525\"}]},\"id\":\"1570\",\"type\":\"Column\"},{\"attributes\":{},\"id\":\"1607\",\"type\":\"BasicTickFormatter\"},{\"attributes\":{},\"id\":\"1617\",\"type\":\"Selection\"},{\"attributes\":{\"args\":{\"cds\":{\"id\":\"1527\"},\"colorby_selector\":{\"id\":\"1525\"},\"render_cds\":{\"id\":\"1526\"},\"x_selector\":{\"id\":\"1523\"},\"xaxis\":[{\"id\":\"1537\"}],\"y_selector\":{\"id\":\"1524\"},\"yaxis\":[{\"id\":\"1541\"}]},\"code\":\"\\n// Extract what we want to color by from selector\\nvar colorby = colorby_selector.value;\\n\\n// View of the colors for convenience\\nvar colors = render_cds.data['color'];\\n\\n// Convenient to have the number of data points\\nvar n = colors.length;\\n\\n// New data\\nrender_cds.data['x'] = cds.data[x_selector.value];\\nrender_cds.data['y'] = cds.data[y_selector.value];\\n\\n// Update colors\\nif (colorby === 'none') {\\n for (var i = 0; i < n; i++) {\\n colors[i] = '#1f77b3';\\n }\\n}\\nelse if (colorby === 'gender') {\\n for (var i = 0; i < n; i++) {\\n if (cds.data['gender'][i] === 'f') {\\n colors[i] = '#1f77b3';\\n }\\n else {\\n colors[i] = '#ff7e0e';\\n }\\n }\\n}\\nelse if (colorby === 'insomnia') {\\n for (var i = 0; i < n; i++) {\\n if (cds.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_cds.change.emit();\\n\"},\"id\":\"1565\",\"type\":\"CustomJS\"},{\"attributes\":{\"axis_label\":\"confidence when correct\",\"formatter\":{\"id\":\"1610\"},\"major_label_policy\":{\"id\":\"1611\"},\"ticker\":{\"id\":\"1542\"}},\"id\":\"1541\",\"type\":\"LinearAxis\"},{\"attributes\":{},\"id\":\"1608\",\"type\":\"AllLabels\"},{\"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\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\",\"#1f77b3\"],\"x\":{\"__ndarray__\":\"AAAAAAAgUkAAAAAAAIBWQAAAAAAAIFdAAAAAAADgVUAAAAAAAEBPQAAAAAAAAElAAAAAAACgVEAAAAAAAOBQQAAAAAAAgFZAAAAAAADAUkAAAAAAAEBPQAAAAAAAwFdAAAAAAAAAVEAAAAAAAABUQAAAAAAAQFBAAAAAAACAUUAAAAAAAIBRQAAAAAAAAFRAAAAAAABAVUAAAAAAAMBSQAAAAAAAgFFAAAAAAABgWEAAAAAAAOBVQAAAAAAAgEZAAAAAAACAUUAAAAAAACBSQAAAAAAAQFVAAAAAAADAUkAAAAAAAOBQQAAAAAAAwFdAAAAAAADgVUAAAAAAACBXQAAAAAAAgFZAAAAAAAAAWUAAAAAAAIBRQAAAAAAAQFVAAAAAAABgU0AAAAAAACBXQAAAAAAAQFVAAAAAAADATEAAAAAAACBXQAAAAAAAQFBAAAAAAADAV0AAAAAAAGBTQAAAAAAAAFRAAAAAAACAVkAAAAAAAABUQAAAAAAA4FVAAAAAAAAgV0AAAAAAAMBSQAAAAAAA4FBAAAAAAABgU0AAAAAAACBSQAAAAAAAIFJAAAAAAABAVUAAAAAAAOBVQAAAAAAA4FVAAAAAAACAVkAAAAAAAOBVQAAAAAAAAFRAAAAAAACAVkAAAAAAAABUQAAAAAAAQFVAAAAAA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AAAAAwFBAAAAAAACgVEAAAAAAAMBQQAAAAAAAAFZAAAAAAADAVEAAAAAAAMBPQAAAAAAAIFRAAAAAAADAUUAAAAAAAMBXQAAAAAAAoFNAAAAAAABASkAAAAAAAEBRQAAAAAAAgE5AAAAAAACAUEAAAAAAAIBSQAAAAAAAAFdAAAAAAAAAVEAAAAAAAABXQAAAAAAAwFRAAAAAAABATkAAAAAAACBSQAAAAAAAYFhAAAAAAAAAUUAAAAAAAMBQQAAAAAAAQFBAAAAAAACAVEAAAAAAAMBSQAAAAAAAgFdAAAAAAABAU0AAAAAAAABXQAAAAAAAQFRAAAAAAAAATUAAAAAAAOBWQAAAAAAAAFlAAAAAAABAVUAAAAAAAIBSQAAAAAAA4FNAAAAAAACgUUAAAAAAAABSQAAAAAAAQFVAAAAAAAAAUEAAAAAAAEBTQAAAAAAAgFJAAAAAAABAUEAAAAAAAEBUQAAAAAAAQFRA\",\"dtype\":\"float64\",\"order\":\"little\",\"shape\":[102]}},\"selected\":{\"id\":\"1614\"},\"selection_policy\":{\"id\":\"1613\"}},\"id\":\"1526\",\"type\":\"ColumnDataSource\"},{\"attributes\":{\"axis\":{\"id\":\"1541\"},\"dimension\":1,\"ticker\":null},\"id\":\"1544\",\"type\":\"Grid\"},{\"attributes\":{\"bottom_units\":\"screen\",\"fill_alpha\":0.5,\"fill_color\":\"lightgrey\",\"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\":\"1551\",\"type\":\"BoxAnnotation\"},{\"attributes\":{},\"id\":\"1542\",\"type\":\"BasicTicker\"},{\"attributes\":{},\"id\":\"1550\",\"type\":\"HelpTool\"},{\"attributes\":{},\"id\":\"1538\",\"type\":\"BasicTicker\"},{\"attributes\":{\"axis\":{\"id\":\"1537\"},\"ticker\":null},\"id\":\"1540\",\"type\":\"Grid\"},{\"attributes\":{\"fill_color\":{\"field\":\"color\"},\"line_color\":{\"field\":\"color\"},\"x\":{\"field\":\"x\"},\"y\":{\"field\":\"y\"}},\"id\":\"1560\",\"type\":\"Circle\"},{\"attributes\":{},\"id\":\"1545\",\"type\":\"PanTool\"},{\"attributes\":{},\"id\":\"1610\",\"type\":\"BasicTickFormatter\"},{\"attributes\":{},\"id\":\"1548\",\"type\":\"SaveTool\"},{\"attributes\":{\"fill_alpha\":{\"value\":0.1},\"fill_color\":{\"field\":\"color\"},\"line_alpha\":{\"value\":0.1},\"line_color\":{\"field\":\"color\"},\"x\":{\"field\":\"x\"},\"y\":{\"field\":\"y\"}},\"id\":\"1561\",\"type\":\"Circle\"},{\"attributes\":{},\"id\":\"1549\",\"type\":\"ResetTool\"},{\"attributes\":{},\"id\":\"1531\",\"type\":\"DataRange1d\"},{\"attributes\":{},\"id\":\"1611\",\"type\":\"AllLabels\"},{\"attributes\":{\"js_property_callbacks\":{\"change:value\":[{\"id\":\"1564\"}]},\"options\":[\"none\",\"gender\",\"insomnia\"],\"title\":\"color by\",\"value\":\"none\",\"width\":200},\"id\":\"1525\",\"type\":\"Select\"},{\"attributes\":{\"source\":{\"id\":\"1526\"}},\"id\":\"1563\",\"type\":\"CDSView\"},{\"attributes\":{\"js_property_callbacks\":{\"change:value\":[{\"id\":\"1565\"}]},\"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\":\"1523\",\"type\":\"Select\"},{\"attributes\":{\"js_property_callbacks\":{\"change:value\":[{\"id\":\"1566\"}]},\"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\":\"1524\",\"type\":\"Select\"},{\"attributes\":{\"data_source\":{\"id\":\"1526\"},\"glyph\":{\"id\":\"1560\"},\"hover_glyph\":null,\"muted_glyph\":null,\"nonselection_glyph\":{\"id\":\"1561\"},\"view\":{\"id\":\"1563\"}},\"id\":\"1562\",\"type\":\"GlyphRenderer\"},{\"attributes\":{\"args\":{\"cds\":{\"id\":\"1527\"},\"colorby_selector\":{\"id\":\"1525\"},\"render_cds\":{\"id\":\"1526\"},\"x_selector\":{\"id\":\"1523\"},\"xaxis\":[{\"id\":\"1537\"}],\"y_selector\":{\"id\":\"1524\"},\"yaxis\":[{\"id\":\"1541\"}]},\"code\":\"\\n// Extract what we want to color by from selector\\nvar colorby = colorby_selector.value;\\n\\n// View of the colors for convenience\\nvar colors = render_cds.data['color'];\\n\\n// Convenient to have the number of data points\\nvar n = colors.length;\\n\\n// New data\\nrender_cds.data['x'] = cds.data[x_selector.value];\\nrender_cds.data['y'] = cds.data[y_selector.value];\\n\\n// Update colors\\nif (colorby === 'none') {\\n for (var i = 0; i < n; i++) {\\n colors[i] = '#1f77b3';\\n }\\n}\\nelse if (colorby === 'gender') {\\n for (var i = 0; i < n; i++) {\\n if (cds.data['gender'][i] === 'f') {\\n colors[i] = '#1f77b3';\\n }\\n else {\\n colors[i] = '#ff7e0e';\\n }\\n }\\n}\\nelse if (colorby === 'insomnia') {\\n for (var i = 0; i < n; i++) {\\n if (cds.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_cds.change.emit();\\n\"},\"id\":\"1566\",\"type\":\"CustomJS\"},{\"attributes\":{},\"id\":\"1606\",\"type\":\"Title\"},{\"attributes\":{},\"id\":\"1533\",\"type\":\"LinearScale\"},{\"attributes\":{\"axis_label\":\"percent correct\",\"formatter\":{\"id\":\"1607\"},\"major_label_policy\":{\"id\":\"1608\"},\"ticker\":{\"id\":\"1538\"}},\"id\":\"1537\",\"type\":\"LinearAxis\"},{\"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__\":\"AAAAAABAV0AAAAAAAMBSQAAAAAAAQFZAAAAAAAAAVkAAAAAAAEBQQAAAAAAAIFBAAAAAAACAUEAAAAAAAABPQAAAAAAAAFFAAAAAAADAUUAAAAAAAIBUQAAAAAAAAFNAAAAAAADgU0AAAAAAAIBLQAAAAAAAQFVAAAAAAACAUUAAAAAAAEBLQAAAAAAAIFZAAAAAAADgVUAAAAAAAABZQAAAAAAAQFNAAAAAAAAAWUAAAAAAAABUQAAAAAAAYFFAAAAAAABAVEAAAAAAAIBJQAAAAAAAoFNAAAAAAACATEAAAAAAAABOQAAAAAAAAFRAAAAAAADAWEAAAAAAAIBTQAAAAAAAoFNAAAAAAACAVkAAAAAAAIBRQAAAAAAAgFJAAAAAAACAR0AAAAAAAABKQAAAAAAAAFVAAAAAAACAT0AAAAAAAABPQAAAAAAAwE1AAAAAAADgUkAAAAAAAIBTQAAAAAAAgE9AAAAAAABAVEAAAAAAAAA4QAAAAAAAAElAAAAAAABAVEAAAAAAAMBQQAAAAAAAQFNAAAAAAAAAWUAAAAAAAABRQAAAAAAAAEhAAAAAAACAUkAAAAAAAIBUQAAAAAAAwFBAAAAAAACgVEAAAAAAAMBQQAAAAAAAAFZAAAAAAADAVEAAAAAAAMBPQAAAAAAAIFR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AAAWUAAAAAAAABOQAAAAAAAQFNAAAAAAAAAS0AAAAAAAIBIQAAAAAAAwFJAAAAAAACASkAAAAAAAABJQAAAAAAAAPh/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__\":\"AAAAAAAgUkAAAAAAAIBWQAAAAAAAIFdAAAAAAADgVUAAAAAAAEBPQAAAAAAAAElAAAAAAACgVEAAAAAAAOBQQAAAAAAAgFZAAAAAAADAUkAAAAAAAEBPQAAAAAAAwFdAAAAAAAAAVEAAAAAAAABUQAAAAAAAQFBAAAAAAACAUUAAAAAAAIBRQAAAAAAAAFRAAAAAAABAVUAAAAAAAMBSQAAAAAAAgFFAAAAAAABgWEAAAAAAAOBVQAAAAAAAgEZAAAAAAACAUUAAAAAAACBSQAAAAAAAQFVAAAAAAADAUkAAAAAAAOBQQAAAAAAAwFdAAAAAAADgVUAAAAAAACBXQAAAAAAAgFZAAAAAAAAAWUAAAAAAAIBRQAAAAAAAQFVAAAAAAABgU0AAAAAAACBXQAAAAAAAQFVAAAAAAADATEAAAAAAACBXQAAAAAAAQFBAAAAAAADAV0AAAAAAAGBTQAAAAAAAAFRAAAAAAACAVkAAAAAAAABUQAAAAAAA4FVAAAAAAAAgV0AAAAAAAMBSQAAAAAAA4FBAAAAAAABgU0AAAAAAACBSQAAAAAAAIFJAAAAAAABAVUAAAAAAAOBVQAAAAAAA4FVAAAAAAACAVkAAAAAAAOBVQAAAAAAAAFRAAAAAAACAVkAAAAAAAABUQAAAAAAAQFVAAAAAAABAVUAAAAAAAGBTQAAAAAAAQFVAAAAAAABAVUAAAAAAAEBVQAAAAAAAYFNAAAAAAACAVkAAAAAAAABZQAAAAAAAQFVAAAAAAADgVUAAAAAAAGBYQAAAAAAAIFdAAAAAAAAAWUAAAAAAAABOQAAAAAAAwFdAAAAAAABgU0AAAAAAAGBTQAAAAAAAoFRAAAAAAAAAREAAAAAAAOBVQAAAAAAAQFVAAAAAAADgVUAAAAAAAGBTQAAAAAAAQE9AAAAAAAAgUkAAAAAAAEBVQAAAAAAAIFdAAAAAAABAVUAAAAAAACBSQAAAAAAAgFZAAAAAAACAVkAAAAAAAIBLQAAAAAAA4FVAAAAAAAAATkAAAAAAAGBTQAAAAAAA4FVAAAAAAADAUkAAAAAAAIBRQAAAAAAAQE9A\",\"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\":\"1617\"},\"selection_policy\":{\"id\":\"1616\"}},\"id\":\"1527\",\"type\":\"ColumnDataSource\"},{\"attributes\":{\"height\":15},\"id\":\"1568\",\"type\":\"Spacer\"},{\"attributes\":{},\"id\":\"1613\",\"type\":\"UnionRenderers\"},{\"attributes\":{},\"id\":\"1529\",\"type\":\"DataRange1d\"},{\"attributes\":{},\"id\":\"1614\",\"type\":\"Selection\"},{\"attributes\":{\"active_multi\":null,\"tools\":[{\"id\":\"1545\"},{\"id\":\"1546\"},{\"id\":\"1547\"},{\"id\":\"1548\"},{\"id\":\"1549\"},{\"id\":\"1550\"}]},\"id\":\"1552\",\"type\":\"Toolbar\"},{\"attributes\":{\"below\":[{\"id\":\"1537\"}],\"center\":[{\"id\":\"1540\"},{\"id\":\"1544\"}],\"frame_height\":250,\"frame_width\":250,\"left\":[{\"id\":\"1541\"}],\"renderers\":[{\"id\":\"1562\"}],\"title\":{\"id\":\"1606\"},\"toolbar\":{\"id\":\"1552\"},\"x_range\":{\"id\":\"1529\"},\"x_scale\":{\"id\":\"1533\"},\"y_range\":{\"id\":\"1531\"},\"y_scale\":{\"id\":\"1535\"}},\"id\":\"1528\",\"subtype\":\"Figure\",\"type\":\"Plot\"},{\"attributes\":{\"height\":15},\"id\":\"1569\",\"type\":\"Spacer\"},{\"attributes\":{\"overlay\":{\"id\":\"1551\"}},\"id\":\"1547\",\"type\":\"BoxZoomTool\"},{\"attributes\":{\"args\":{\"cds\":{\"id\":\"1527\"},\"colorby_selector\":{\"id\":\"1525\"},\"render_cds\":{\"id\":\"1526\"},\"x_selector\":{\"id\":\"1523\"},\"xaxis\":[{\"id\":\"1537\"}],\"y_selector\":{\"id\":\"1524\"},\"yaxis\":[{\"id\":\"1541\"}]},\"code\":\"\\n// Extract what we want to color by from selector\\nvar colorby = colorby_selector.value;\\n\\n// View of the colors for convenience\\nvar colors = render_cds.data['color'];\\n\\n// Convenient to have the number of data points\\nvar n = colors.length;\\n\\n// New data\\nrender_cds.data['x'] = cds.data[x_selector.value];\\nrender_cds.data['y'] = cds.data[y_selector.value];\\n\\n// Update colors\\nif (colorby === 'none') {\\n for (var i = 0; i < n; i++) {\\n colors[i] = '#1f77b3';\\n }\\n}\\nelse if (colorby === 'gender') {\\n for (var i = 0; i < n; i++) {\\n if (cds.data['gender'][i] === 'f') {\\n colors[i] = '#1f77b3';\\n }\\n else {\\n colors[i] = '#ff7e0e';\\n }\\n }\\n}\\nelse if (colorby === 'insomnia') {\\n for (var i = 0; i < n; i++) {\\n if (cds.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_cds.change.emit();\\n\"},\"id\":\"1564\",\"type\":\"CustomJS\"}],\"root_ids\":[\"1571\"]},\"title\":\"Bokeh Application\",\"version\":\"2.3.2\"}};\n", " var render_items = [{\"docid\":\"f8fbcf71-a69f-4b94-b088-617867eaab0b\",\"root_ids\":[\"1571\"],\"roots\":{\"1571\":\"6869ea7f-08ad-483e-adf4-f421088ece7f\"}}];\n", " root.Bokeh.embed.embed_items_notebook(docs_json, render_items);\n", "\n", " }\n", " if (root.Bokeh !== undefined) {\n", " embed_document(root);\n", " } else {\n", " var attempts = 0;\n", " var timer = setInterval(function(root) {\n", " if (root.Bokeh !== undefined) {\n", " clearInterval(timer);\n", " embed_document(root);\n", " } else {\n", " attempts++;\n", " if (attempts > 100) {\n", " clearInterval(timer);\n", " console.log(\"Bokeh: ERROR: Unable to run BokehJS code because BokehJS library is missing\");\n", " }\n", " }\n", " }, 10, root)\n", " }\n", "})(window);" ], "application/vnd.bokehjs_exec.v0+json": "" }, "metadata": { "application/vnd.bokehjs_exec.v0+json": { "id": "1571" } }, "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": 25, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/Users/bois/opt/anaconda3/lib/python3.8/site-packages/bokeh/io/saving.py:126: UserWarning: save() called but no resources were supplied and output_file(...) was never called, defaulting to resources.CDN\n", " warn(\"save() called but no resources were supplied and output_file(...) was never called, defaulting to resources.CDN\")\n", "/Users/bois/opt/anaconda3/lib/python3.8/site-packages/bokeh/io/saving.py:139: UserWarning: save() called but no title was supplied and output_file(...) was never called, using default title 'Bokeh Plot'\n", " warn(\"save() called but no title was supplied and output_file(...) was never called, using default title 'Bokeh Plot'\")\n" ] }, { "data": { "text/plain": [ "'/Users/bois/Dropbox/git/programming_bootcamp/2021/content/lessons/sleep_facial_recognition.html'" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bokeh.io.save(layout, 'sleep_facial_recognition.html')" ] }, { "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": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Python implementation: CPython\n", "Python version : 3.8.10\n", "IPython version : 7.22.0\n", "\n", "numpy : 1.20.2\n", "pandas : 1.2.4\n", "bokeh : 2.3.2\n", "jupyterlab: 3.0.14\n", "\n" ] } ], "source": [ "%load_ext watermark\n", "%watermark -v -p numpy,pandas,bokeh,jupyterlab" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.10" } }, "nbformat": 4, "nbformat_minor": 4 }