{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Plots with categorical variables\n", "\n", "[Data set download](https://s3.amazonaws.com/bebi103.caltech.edu/data/gfmt_sleep.csv)\n", "\n", "
" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "nbsphinx": "hidden", "tags": [] }, "outputs": [], "source": [ "# Colab setup ------------------\n", "import os, sys, subprocess\n", "if \"google.colab\" in sys.modules:\n", " cmd = \"pip install --upgrade watermark\"\n", " process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n", " stdout, stderr = process.communicate()\n", " data_path = \"https://s3.amazonaws.com/bebi103.caltech.edu/data/\"\n", "else:\n", " data_path = \"../data/\"" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "
\n", " \n", " Loading BokehJS ...\n", "
\n" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/javascript": [ "(function(root) {\n", " function now() {\n", " return new Date();\n", " }\n", "\n", " const force = true;\n", "\n", " if (typeof root._bokeh_onload_callbacks === \"undefined\" || force === true) {\n", " root._bokeh_onload_callbacks = [];\n", " root._bokeh_is_loading = undefined;\n", " }\n", "\n", "const JS_MIME_TYPE = 'application/javascript';\n", " const HTML_MIME_TYPE = 'text/html';\n", " const EXEC_MIME_TYPE = 'application/vnd.bokehjs_exec.v0+json';\n", " const CLASS_NAME = 'output_bokeh rendered_html';\n", "\n", " /**\n", " * Render data to the DOM node\n", " */\n", " function render(props, node) {\n", " const script = document.createElement(\"script\");\n", " node.appendChild(script);\n", " }\n", "\n", " /**\n", " * Handle when an output is cleared or removed\n", " */\n", " function handleClearOutput(event, handle) {\n", " const cell = handle.cell;\n", "\n", " const id = cell.output_area._bokeh_element_id;\n", " const server_id = cell.output_area._bokeh_server_id;\n", " // Clean up Bokeh references\n", " if (id != null && id in Bokeh.index) {\n", " Bokeh.index[id].model.document.clear();\n", " delete Bokeh.index[id];\n", " }\n", "\n", " if (server_id !== undefined) {\n", " // Clean up Bokeh references\n", " const cmd_clean = \"from bokeh.io.state import curstate; print(curstate().uuid_to_server['\" + server_id + \"'].get_sessions()[0].document.roots[0]._id)\";\n", " cell.notebook.kernel.execute(cmd_clean, {\n", " iopub: {\n", " output: function(msg) {\n", " const id = msg.content.text.trim();\n", " if (id in Bokeh.index) {\n", " Bokeh.index[id].model.document.clear();\n", " delete Bokeh.index[id];\n", " }\n", " }\n", " }\n", " });\n", " // Destroy server and session\n", " const cmd_destroy = \"import bokeh.io.notebook as ion; ion.destroy_server('\" + server_id + \"')\";\n", " cell.notebook.kernel.execute(cmd_destroy);\n", " }\n", " }\n", "\n", " /**\n", " * Handle when a new output is added\n", " */\n", " function handleAddOutput(event, handle) {\n", " const output_area = handle.output_area;\n", " const output = handle.output;\n", "\n", " // limit handleAddOutput to display_data with EXEC_MIME_TYPE content only\n", " if ((output.output_type != \"display_data\") || (!Object.prototype.hasOwnProperty.call(output.data, EXEC_MIME_TYPE))) {\n", " return\n", " }\n", "\n", " const toinsert = output_area.element.find(\".\" + CLASS_NAME.split(' ')[0]);\n", "\n", " if (output.metadata[EXEC_MIME_TYPE][\"id\"] !== undefined) {\n", " toinsert[toinsert.length - 1].firstChild.textContent = output.data[JS_MIME_TYPE];\n", " // store reference to embed id on output_area\n", " output_area._bokeh_element_id = output.metadata[EXEC_MIME_TYPE][\"id\"];\n", " }\n", " if (output.metadata[EXEC_MIME_TYPE][\"server_id\"] !== undefined) {\n", " const bk_div = document.createElement(\"div\");\n", " bk_div.innerHTML = output.data[HTML_MIME_TYPE];\n", " const script_attrs = bk_div.children[0].attributes;\n", " for (let i = 0; i < script_attrs.length; i++) {\n", " toinsert[toinsert.length - 1].firstChild.setAttribute(script_attrs[i].name, script_attrs[i].value);\n", " toinsert[toinsert.length - 1].firstChild.textContent = bk_div.children[0].textContent\n", " }\n", " // store reference to server id on output_area\n", " output_area._bokeh_server_id = output.metadata[EXEC_MIME_TYPE][\"server_id\"];\n", " }\n", " }\n", "\n", " function register_renderer(events, OutputArea) {\n", "\n", " function append_mime(data, metadata, element) {\n", " // create a DOM node to render to\n", " const toinsert = this.create_output_subarea(\n", " metadata,\n", " CLASS_NAME,\n", " EXEC_MIME_TYPE\n", " );\n", " this.keyboard_manager.register_events(toinsert);\n", " // Render to node\n", " const props = {data: data, metadata: metadata[EXEC_MIME_TYPE]};\n", " render(props, toinsert[toinsert.length - 1]);\n", " element.append(toinsert);\n", " return toinsert\n", " }\n", "\n", " /* Handle when an output is cleared or removed */\n", " events.on('clear_output.CodeCell', handleClearOutput);\n", " events.on('delete.Cell', handleClearOutput);\n", "\n", " /* Handle when a new output is added */\n", " events.on('output_added.OutputArea', handleAddOutput);\n", "\n", " /**\n", " * Register the mime type and append_mime function with output_area\n", " */\n", " OutputArea.prototype.register_mime_type(EXEC_MIME_TYPE, append_mime, {\n", " /* Is output safe? */\n", " safe: true,\n", " /* Index of renderer in `output_area.display_order` */\n", " index: 0\n", " });\n", " }\n", "\n", " // register the mime type if in Jupyter Notebook environment and previously unregistered\n", " if (root.Jupyter !== undefined) {\n", " const events = require('base/js/events');\n", " const OutputArea = require('notebook/js/outputarea').OutputArea;\n", "\n", " if (OutputArea.prototype.mime_types().indexOf(EXEC_MIME_TYPE) == -1) {\n", " register_renderer(events, OutputArea);\n", " }\n", " }\n", " if (typeof (root._bokeh_timeout) === \"undefined\" || force === true) {\n", " root._bokeh_timeout = Date.now() + 5000;\n", " root._bokeh_failed_load = false;\n", " }\n", "\n", " const NB_LOAD_WARNING = {'data': {'text/html':\n", " \"
\\n\"+\n", " \"

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

\\n\"+\n", " \"\\n\"+\n", " \"\\n\"+\n", " \"from bokeh.resources import INLINE\\n\"+\n", " \"output_notebook(resources=INLINE)\\n\"+\n", " \"\\n\"+\n", " \"
\"}};\n", "\n", " function display_loaded() {\n", " const el = document.getElementById(\"dd96a900-5f5a-4c3d-a058-3e7a32d20fac\");\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", " function run_callbacks() {\n", " try {\n", " root._bokeh_onload_callbacks.forEach(function(callback) {\n", " if (callback != null)\n", " callback();\n", " });\n", " } finally {\n", " delete root._bokeh_onload_callbacks\n", " }\n", " console.debug(\"Bokeh: all callbacks have finished\");\n", " }\n", "\n", " function load_libs(css_urls, js_urls, callback) {\n", " if (css_urls == null) css_urls = [];\n", " if (js_urls == null) js_urls = [];\n", "\n", " root._bokeh_onload_callbacks.push(callback);\n", " if (root._bokeh_is_loading > 0) {\n", " console.debug(\"Bokeh: BokehJS is being loaded, scheduling callback at\", now());\n", " return null;\n", " }\n", " if (js_urls == null || js_urls.length === 0) {\n", " run_callbacks();\n", " return null;\n", " }\n", " console.debug(\"Bokeh: BokehJS not loaded, scheduling load and callback at\", now());\n", " root._bokeh_is_loading = css_urls.length + js_urls.length;\n", "\n", " function on_load() {\n", " root._bokeh_is_loading--;\n", " if (root._bokeh_is_loading === 0) {\n", " console.debug(\"Bokeh: all BokehJS libraries/stylesheets loaded\");\n", " run_callbacks()\n", " }\n", " }\n", "\n", " function on_error(url) {\n", " console.error(\"failed to load \" + url);\n", " }\n", "\n", " for (let i = 0; i < css_urls.length; i++) {\n", " const url = css_urls[i];\n", " const element = document.createElement(\"link\");\n", " element.onload = on_load;\n", " element.onerror = on_error.bind(null, url);\n", " element.rel = \"stylesheet\";\n", " element.type = \"text/css\";\n", " element.href = url;\n", " console.debug(\"Bokeh: injecting link tag for BokehJS stylesheet: \", url);\n", " document.body.appendChild(element);\n", " }\n", "\n", " for (let i = 0; i < js_urls.length; i++) {\n", " const url = js_urls[i];\n", " const element = document.createElement('script');\n", " element.onload = on_load;\n", " element.onerror = on_error.bind(null, url);\n", " element.async = false;\n", " element.src = url;\n", " console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n", " document.head.appendChild(element);\n", " }\n", " };\n", "\n", " function inject_raw_css(css) {\n", " const element = document.createElement(\"style\");\n", " element.appendChild(document.createTextNode(css));\n", " document.body.appendChild(element);\n", " }\n", "\n", " const js_urls = [\"https://cdn.bokeh.org/bokeh/release/bokeh-3.2.1.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-gl-3.2.1.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-3.2.1.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-3.2.1.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-mathjax-3.2.1.min.js\"];\n", " const css_urls = [];\n", "\n", " const inline_js = [ function(Bokeh) {\n", " Bokeh.set_log_level(\"info\");\n", " },\n", "function(Bokeh) {\n", " }\n", " ];\n", "\n", " function run_inline_js() {\n", " if (root.Bokeh !== undefined || force === true) {\n", " for (let i = 0; i < inline_js.length; i++) {\n", " inline_js[i].call(root, root.Bokeh);\n", " }\n", "if (force === true) {\n", " display_loaded();\n", " }} else if (Date.now() < root._bokeh_timeout) {\n", " setTimeout(run_inline_js, 100);\n", " } else if (!root._bokeh_failed_load) {\n", " console.log(\"Bokeh: BokehJS failed to load within specified timeout.\");\n", " root._bokeh_failed_load = true;\n", " } else if (force !== true) {\n", " const cell = $(document.getElementById(\"dd96a900-5f5a-4c3d-a058-3e7a32d20fac\")).parents('.cell').data().cell;\n", " cell.output_area.append_execute_result(NB_LOAD_WARNING)\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": "(function(root) {\n function now() {\n return new Date();\n }\n\n const force = true;\n\n if (typeof root._bokeh_onload_callbacks === \"undefined\" || force === true) {\n root._bokeh_onload_callbacks = [];\n root._bokeh_is_loading = undefined;\n }\n\n\n if (typeof (root._bokeh_timeout) === \"undefined\" || force === true) {\n root._bokeh_timeout = Date.now() + 5000;\n root._bokeh_failed_load = false;\n }\n\n const NB_LOAD_WARNING = {'data': {'text/html':\n \"
\\n\"+\n \"

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

\\n\"+\n \"\\n\"+\n \"\\n\"+\n \"from bokeh.resources import INLINE\\n\"+\n \"output_notebook(resources=INLINE)\\n\"+\n \"\\n\"+\n \"
\"}};\n\n function display_loaded() {\n const el = document.getElementById(\"dd96a900-5f5a-4c3d-a058-3e7a32d20fac\");\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 function run_callbacks() {\n try {\n root._bokeh_onload_callbacks.forEach(function(callback) {\n if (callback != null)\n callback();\n });\n } finally {\n delete root._bokeh_onload_callbacks\n }\n console.debug(\"Bokeh: all callbacks have finished\");\n }\n\n function load_libs(css_urls, js_urls, callback) {\n if (css_urls == null) css_urls = [];\n if (js_urls == null) js_urls = [];\n\n root._bokeh_onload_callbacks.push(callback);\n if (root._bokeh_is_loading > 0) {\n console.debug(\"Bokeh: BokehJS is being loaded, scheduling callback at\", now());\n return null;\n }\n if (js_urls == null || js_urls.length === 0) {\n run_callbacks();\n return null;\n }\n console.debug(\"Bokeh: BokehJS not loaded, scheduling load and callback at\", now());\n root._bokeh_is_loading = css_urls.length + js_urls.length;\n\n function on_load() {\n root._bokeh_is_loading--;\n if (root._bokeh_is_loading === 0) {\n console.debug(\"Bokeh: all BokehJS libraries/stylesheets loaded\");\n run_callbacks()\n }\n }\n\n function on_error(url) {\n console.error(\"failed to load \" + url);\n }\n\n for (let i = 0; i < css_urls.length; i++) {\n const url = css_urls[i];\n const element = document.createElement(\"link\");\n element.onload = on_load;\n element.onerror = on_error.bind(null, url);\n element.rel = \"stylesheet\";\n element.type = \"text/css\";\n element.href = url;\n console.debug(\"Bokeh: injecting link tag for BokehJS stylesheet: \", url);\n document.body.appendChild(element);\n }\n\n for (let i = 0; i < js_urls.length; i++) {\n const url = js_urls[i];\n const element = document.createElement('script');\n element.onload = on_load;\n element.onerror = on_error.bind(null, url);\n element.async = false;\n element.src = url;\n console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n document.head.appendChild(element);\n }\n };\n\n function inject_raw_css(css) {\n const element = document.createElement(\"style\");\n element.appendChild(document.createTextNode(css));\n document.body.appendChild(element);\n }\n\n const js_urls = [\"https://cdn.bokeh.org/bokeh/release/bokeh-3.2.1.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-gl-3.2.1.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-3.2.1.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-3.2.1.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-mathjax-3.2.1.min.js\"];\n const css_urls = [];\n\n const inline_js = [ function(Bokeh) {\n Bokeh.set_log_level(\"info\");\n },\nfunction(Bokeh) {\n }\n ];\n\n function run_inline_js() {\n if (root.Bokeh !== undefined || force === true) {\n for (let i = 0; i < inline_js.length; i++) {\n inline_js[i].call(root, root.Bokeh);\n }\nif (force === true) {\n display_loaded();\n }} else if (Date.now() < root._bokeh_timeout) {\n setTimeout(run_inline_js, 100);\n } else if (!root._bokeh_failed_load) {\n console.log(\"Bokeh: BokehJS failed to load within specified timeout.\");\n root._bokeh_failed_load = true;\n } else if (force !== true) {\n const cell = $(document.getElementById(\"dd96a900-5f5a-4c3d-a058-3e7a32d20fac\")).parents('.cell').data().cell;\n cell.output_area.append_execute_result(NB_LOAD_WARNING)\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", "\n", "import bokeh.models\n", "import bokeh.plotting\n", "import bokeh.io\n", "bokeh.io.output_notebook()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "## Types of data for plots\n", "\n", "Let us first consider the different kinds of data we may encounter as we think about constructing a plot.\n", "\n", "- **Quantitative** data may have continuously varying (and therefore ordered) values.\n", "- **Categorical** data has discrete, unordered values that a variable can take.\n", "- **Ordinal** data has discrete, ordered values. Integers are a classic example.\n", "- **Temporal** data refers to time, which can be represented as dates.\n", "\n", "In practice, ordinal data can be cast as quantitative or treated as categorical with an ordering enforced on the categories (e.g., categorical data `[1, 2, 3]` becomes `['1', '2', '3']`.). Temporal data can also be cast as quantitative, (e.g., seconds from the start time). We will therefore focus out attention on quantitative and categorical data.\n", "\n", "When we made scatter plots, both types of data were quantitative. We did actually incorporate categorical information in the form of colors of the glyph (insomniacs and normal sleepers being colored differently) and in tooltips.\n", "\n", "But what if we wanted a single type of measurement, such as percent correct in the facial identification, but were interested in delineating performance of insomniacs and normal sleepers. Here, we have the quantitative percent correct data and the categorical sleeper type. One of our axes is now categorical.\n", "\n", "Note that this kind of plot is commonly encountered in the biological sciences. We repeat a measurement many times for given test conditions and wish to compare the results. The different conditions are the categories, and the axis along which the conditions are represented is called a categorical axis. The quantitative axis contains the result of the measurements from each condition.\n", "\n", "
\n", "\n", "_The rest of this lesson is mostly for reference so you can see how to handle categorical axes with Bokeh. In practice, we will mostly be using [iqplot](http://iqplot.github.io/) to do this and it is done for your automatically. You may therefore skip the rest of this notebook if you like._\n", "\n", "_That said, for some plotting applications, you may need to adjust details or do things outside of iqplot's capabilities, so the contents of this lesson can be useful._" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Making a bar graph with Bokeh\n", "\n", "To demonstrate how to set up a categorical axis with Bokeh, I will make a bar graph of the mean percent correct for insomniacs and normal sleepers. But before I even begin this, I will give you the following piece of advice: *Don't make bar graphs.* More on that in a moment." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Setting up a data frame for plotting\n", "\n", "Before making a plot, we need to set up a data frame amenable for the type of plot we want. We start by reading in the data set and computing the `'insomnia'` column, which gives `True`s and `False`s, as we've done in the preceding parts of this lesson." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "fname = os.path.join(data_path, \"gfmt_sleep.csv\")\n", "df = pd.read_csv(fname, na_values=\"*\")\n", "df[\"insomnia\"] = df[\"sci\"] <= 16" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For convenience in plotting the categorical axis, we would rather not have the values on the axis be `True` or `False`, but something more descriptive, like _insomniac_ and _normal_. So, let's make a column in the data frame, `'sleeper'` that has that for us. We use the `apply()` method of the data frame to apply a function that returns the string `'insomniac'` if the entry is in the `'insomnia'` column is `True` and `'normal'` otherwise." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "df[\"sleeper\"] = df[\"insomnia\"].apply(lambda x: \"insomniac\" if x else \"normal\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next, we need to make a data frame that has the mean percent correct for each of the two categories of sleeper. We have decided that it is the mean of the respective measurements that will set the height of the bars." ] }, { "cell_type": "code", "execution_count": 5, "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", "
sleeperpercent correct
0insomniac76.100000
1normal81.461039
\n", "
" ], "text/plain": [ " sleeper percent correct\n", "0 insomniac 76.100000\n", "1 normal 81.461039" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df_mean = df.groupby(\"sleeper\")[\"percent correct\"].mean().reset_index()\n", "\n", "# Take a look\n", "df_mean" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we're ready to make the bar graph. Note that we now have only two data points that we are showing on the plot. We have decided to throw out a **lot** of information from the data we collected to display only two values. Does this strike you as a terrible idea? It should. **Don't do this.** We're just doing it to show how categorical axes are set up using Bokeh." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Setting up categorical axes\n", "\n", "To set up a categorical axis, you need to specify the `x_range` (or `y_range` if you want the y-axis to be categorical) as a list with the categories you want on the axis when you instantiate the figure. I will make a horizontal bar graph, so I will specify `y_range`. I also want my quantitative axis (x in this case) to go from zero to 100, since it signifies a percent. Also, when I instantiate this figure, because it is not very tall and I do not want the reset tool cut off, I will also explicitly set the tools I want in the toolbar." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "p = bokeh.plotting.figure(\n", " height=200,\n", " width=400,\n", " x_axis_label=\"percent correct\",\n", " x_range=[0, 100],\n", " y_range=df_mean[\"sleeper\"].unique(),\n", " tools=\"save\",\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that we have the figure, we can put the bars on. The `p.hbar()` method populates the figure with horizontal bar glyphs. The `right` kwarg says what column of the data source dictates how far to the right to show the bar, while the `height` kwarg says how think the bars are.\n", "\n", "I will also ensure the quantitative axis starts at zero and turn off the grid lines on the categorical axis, which is commonly done." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "
\n" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/javascript": [ "(function(root) {\n", " function embed_document(root) {\n", " const docs_json = {\"f6a1cb2e-3637-4c2a-abe5-3eaa8a1c1eee\":{\"version\":\"3.2.1\",\"title\":\"Bokeh Application\",\"roots\":[{\"type\":\"object\",\"name\":\"Figure\",\"id\":\"p1001\",\"attributes\":{\"width\":400,\"height\":200,\"x_range\":{\"type\":\"object\",\"name\":\"Range1d\",\"id\":\"p1010\",\"attributes\":{\"end\":100}},\"y_range\":{\"type\":\"object\",\"name\":\"FactorRange\",\"id\":\"p1011\",\"attributes\":{\"factors\":[\"insomniac\",\"normal\"]}},\"x_scale\":{\"type\":\"object\",\"name\":\"LinearScale\",\"id\":\"p1012\"},\"y_scale\":{\"type\":\"object\",\"name\":\"CategoricalScale\",\"id\":\"p1013\"},\"title\":{\"type\":\"object\",\"name\":\"Title\",\"id\":\"p1008\"},\"renderers\":[{\"type\":\"object\",\"name\":\"GlyphRenderer\",\"id\":\"p1034\",\"attributes\":{\"data_source\":{\"type\":\"object\",\"name\":\"ColumnDataSource\",\"id\":\"p1025\",\"attributes\":{\"selected\":{\"type\":\"object\",\"name\":\"Selection\",\"id\":\"p1026\",\"attributes\":{\"indices\":[],\"line_indices\":[]}},\"selection_policy\":{\"type\":\"object\",\"name\":\"UnionRenderers\",\"id\":\"p1027\"},\"data\":{\"type\":\"map\",\"entries\":[[\"index\",{\"type\":\"ndarray\",\"array\":{\"type\":\"bytes\",\"data\":\"AAAAAAEAAAA=\"},\"shape\":[2],\"dtype\":\"int32\",\"order\":\"little\"}],[\"sleeper\",{\"type\":\"ndarray\",\"array\":[\"insomniac\",\"normal\"],\"shape\":[2],\"dtype\":\"object\",\"order\":\"little\"}],[\"percent correct\",{\"type\":\"ndarray\",\"array\":{\"type\":\"bytes\",\"data\":\"ZmZmZmYGU0AH9o6pgV1UQA==\"},\"shape\":[2],\"dtype\":\"float64\",\"order\":\"little\"}]]}}},\"view\":{\"type\":\"object\",\"name\":\"CDSView\",\"id\":\"p1035\",\"attributes\":{\"filter\":{\"type\":\"object\",\"name\":\"AllIndices\",\"id\":\"p1036\"}}},\"glyph\":{\"type\":\"object\",\"name\":\"HBar\",\"id\":\"p1031\",\"attributes\":{\"y\":{\"type\":\"field\",\"field\":\"sleeper\"},\"height\":{\"type\":\"value\",\"value\":0.6},\"right\":{\"type\":\"field\",\"field\":\"percent correct\"},\"line_color\":{\"type\":\"value\",\"value\":\"#1f77b4\"},\"fill_color\":{\"type\":\"value\",\"value\":\"#1f77b4\"}}},\"nonselection_glyph\":{\"type\":\"object\",\"name\":\"HBar\",\"id\":\"p1032\",\"attributes\":{\"y\":{\"type\":\"field\",\"field\":\"sleeper\"},\"height\":{\"type\":\"value\",\"value\":0.6},\"right\":{\"type\":\"field\",\"field\":\"percent correct\"},\"line_color\":{\"type\":\"value\",\"value\":\"#1f77b4\"},\"line_alpha\":{\"type\":\"value\",\"value\":0.1},\"fill_color\":{\"type\":\"value\",\"value\":\"#1f77b4\"},\"fill_alpha\":{\"type\":\"value\",\"value\":0.1},\"hatch_alpha\":{\"type\":\"value\",\"value\":0.1}}},\"muted_glyph\":{\"type\":\"object\",\"name\":\"HBar\",\"id\":\"p1033\",\"attributes\":{\"y\":{\"type\":\"field\",\"field\":\"sleeper\"},\"height\":{\"type\":\"value\",\"value\":0.6},\"right\":{\"type\":\"field\",\"field\":\"percent correct\"},\"line_color\":{\"type\":\"value\",\"value\":\"#1f77b4\"},\"line_alpha\":{\"type\":\"value\",\"value\":0.2},\"fill_color\":{\"type\":\"value\",\"value\":\"#1f77b4\"},\"fill_alpha\":{\"type\":\"value\",\"value\":0.2},\"hatch_alpha\":{\"type\":\"value\",\"value\":0.2}}}}}],\"toolbar\":{\"type\":\"object\",\"name\":\"Toolbar\",\"id\":\"p1009\",\"attributes\":{\"tools\":[{\"type\":\"object\",\"name\":\"SaveTool\",\"id\":\"p1024\"}]}},\"left\":[{\"type\":\"object\",\"name\":\"CategoricalAxis\",\"id\":\"p1019\",\"attributes\":{\"ticker\":{\"type\":\"object\",\"name\":\"CategoricalTicker\",\"id\":\"p1020\"},\"formatter\":{\"type\":\"object\",\"name\":\"CategoricalTickFormatter\",\"id\":\"p1021\"},\"major_label_policy\":{\"type\":\"object\",\"name\":\"AllLabels\",\"id\":\"p1022\"}}}],\"below\":[{\"type\":\"object\",\"name\":\"LinearAxis\",\"id\":\"p1014\",\"attributes\":{\"ticker\":{\"type\":\"object\",\"name\":\"BasicTicker\",\"id\":\"p1015\",\"attributes\":{\"mantissas\":[1,2,5]}},\"formatter\":{\"type\":\"object\",\"name\":\"BasicTickFormatter\",\"id\":\"p1016\"},\"axis_label\":\"percent correct\",\"major_label_policy\":{\"type\":\"object\",\"name\":\"AllLabels\",\"id\":\"p1017\"}}}],\"center\":[{\"type\":\"object\",\"name\":\"Grid\",\"id\":\"p1018\",\"attributes\":{\"axis\":{\"id\":\"p1014\"}}},{\"type\":\"object\",\"name\":\"Grid\",\"id\":\"p1023\",\"attributes\":{\"dimension\":1,\"axis\":{\"id\":\"p1019\"},\"grid_line_color\":null}}]}}]}};\n", " const render_items = [{\"docid\":\"f6a1cb2e-3637-4c2a-abe5-3eaa8a1c1eee\",\"roots\":{\"p1001\":\"c0b3cbf1-489f-4eb9-8419-6c0762b0a03a\"},\"root_ids\":[\"p1001\"]}];\n", " root.Bokeh.embed.embed_items_notebook(docs_json, render_items);\n", " }\n", " if (root.Bokeh !== undefined) {\n", " embed_document(root);\n", " } else {\n", " let attempts = 0;\n", " const timer = setInterval(function(root) {\n", " if (root.Bokeh !== undefined) {\n", " clearInterval(timer);\n", " embed_document(root);\n", " } else {\n", " attempts++;\n", " if (attempts > 100) {\n", " clearInterval(timer);\n", " console.log(\"Bokeh: ERROR: Unable to run BokehJS code because BokehJS library is missing\");\n", " }\n", " }\n", " }, 10, root)\n", " }\n", "})(window);" ], "application/vnd.bokehjs_exec.v0+json": "" }, "metadata": { "application/vnd.bokehjs_exec.v0+json": { "id": "p1001" } }, "output_type": "display_data" } ], "source": [ "p.hbar(\n", " source=df_mean,\n", " y=\"sleeper\",\n", " right=\"percent correct\",\n", " height=0.6,\n", ")\n", "\n", "# Turn off gridlines on categorical axis\n", "p.ygrid.grid_line_color = None\n", "\n", "bokeh.io.show(p)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We similarly make vertical bar graphs specifying `x_range` and using `p.vbar()`." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "
\n" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/javascript": [ "(function(root) {\n", " function embed_document(root) {\n", " const docs_json = {\"f34f9bde-1da9-4dae-b9d2-3c97437b5a51\":{\"version\":\"3.2.1\",\"title\":\"Bokeh Application\",\"roots\":[{\"type\":\"object\",\"name\":\"Figure\",\"id\":\"p1039\",\"attributes\":{\"width\":250,\"height\":250,\"x_range\":{\"type\":\"object\",\"name\":\"FactorRange\",\"id\":\"p1048\",\"attributes\":{\"factors\":[\"normal\",\"insomniac\"]}},\"y_range\":{\"type\":\"object\",\"name\":\"Range1d\",\"id\":\"p1049\",\"attributes\":{\"end\":100}},\"x_scale\":{\"type\":\"object\",\"name\":\"CategoricalScale\",\"id\":\"p1050\"},\"y_scale\":{\"type\":\"object\",\"name\":\"LinearScale\",\"id\":\"p1051\"},\"title\":{\"type\":\"object\",\"name\":\"Title\",\"id\":\"p1046\"},\"renderers\":[{\"type\":\"object\",\"name\":\"GlyphRenderer\",\"id\":\"p1078\",\"attributes\":{\"data_source\":{\"type\":\"object\",\"name\":\"ColumnDataSource\",\"id\":\"p1069\",\"attributes\":{\"selected\":{\"type\":\"object\",\"name\":\"Selection\",\"id\":\"p1070\",\"attributes\":{\"indices\":[],\"line_indices\":[]}},\"selection_policy\":{\"type\":\"object\",\"name\":\"UnionRenderers\",\"id\":\"p1071\"},\"data\":{\"type\":\"map\",\"entries\":[[\"index\",{\"type\":\"ndarray\",\"array\":{\"type\":\"bytes\",\"data\":\"AAAAAAEAAAA=\"},\"shape\":[2],\"dtype\":\"int32\",\"order\":\"little\"}],[\"sleeper\",{\"type\":\"ndarray\",\"array\":[\"insomniac\",\"normal\"],\"shape\":[2],\"dtype\":\"object\",\"order\":\"little\"}],[\"percent correct\",{\"type\":\"ndarray\",\"array\":{\"type\":\"bytes\",\"data\":\"ZmZmZmYGU0AH9o6pgV1UQA==\"},\"shape\":[2],\"dtype\":\"float64\",\"order\":\"little\"}]]}}},\"view\":{\"type\":\"object\",\"name\":\"CDSView\",\"id\":\"p1079\",\"attributes\":{\"filter\":{\"type\":\"object\",\"name\":\"AllIndices\",\"id\":\"p1080\"}}},\"glyph\":{\"type\":\"object\",\"name\":\"VBar\",\"id\":\"p1075\",\"attributes\":{\"x\":{\"type\":\"field\",\"field\":\"sleeper\"},\"width\":{\"type\":\"value\",\"value\":0.6},\"top\":{\"type\":\"field\",\"field\":\"percent correct\"},\"line_color\":{\"type\":\"value\",\"value\":\"#1f77b4\"},\"fill_color\":{\"type\":\"value\",\"value\":\"#1f77b4\"}}},\"nonselection_glyph\":{\"type\":\"object\",\"name\":\"VBar\",\"id\":\"p1076\",\"attributes\":{\"x\":{\"type\":\"field\",\"field\":\"sleeper\"},\"width\":{\"type\":\"value\",\"value\":0.6},\"top\":{\"type\":\"field\",\"field\":\"percent correct\"},\"line_color\":{\"type\":\"value\",\"value\":\"#1f77b4\"},\"line_alpha\":{\"type\":\"value\",\"value\":0.1},\"fill_color\":{\"type\":\"value\",\"value\":\"#1f77b4\"},\"fill_alpha\":{\"type\":\"value\",\"value\":0.1},\"hatch_alpha\":{\"type\":\"value\",\"value\":0.1}}},\"muted_glyph\":{\"type\":\"object\",\"name\":\"VBar\",\"id\":\"p1077\",\"attributes\":{\"x\":{\"type\":\"field\",\"field\":\"sleeper\"},\"width\":{\"type\":\"value\",\"value\":0.6},\"top\":{\"type\":\"field\",\"field\":\"percent correct\"},\"line_color\":{\"type\":\"value\",\"value\":\"#1f77b4\"},\"line_alpha\":{\"type\":\"value\",\"value\":0.2},\"fill_color\":{\"type\":\"value\",\"value\":\"#1f77b4\"},\"fill_alpha\":{\"type\":\"value\",\"value\":0.2},\"hatch_alpha\":{\"type\":\"value\",\"value\":0.2}}}}}],\"toolbar\":{\"type\":\"object\",\"name\":\"Toolbar\",\"id\":\"p1047\",\"attributes\":{\"tools\":[{\"type\":\"object\",\"name\":\"PanTool\",\"id\":\"p1062\"},{\"type\":\"object\",\"name\":\"WheelZoomTool\",\"id\":\"p1063\"},{\"type\":\"object\",\"name\":\"BoxZoomTool\",\"id\":\"p1064\",\"attributes\":{\"overlay\":{\"type\":\"object\",\"name\":\"BoxAnnotation\",\"id\":\"p1065\",\"attributes\":{\"syncable\":false,\"level\":\"overlay\",\"visible\":false,\"left_units\":\"canvas\",\"right_units\":\"canvas\",\"bottom_units\":\"canvas\",\"top_units\":\"canvas\",\"line_color\":\"black\",\"line_alpha\":1.0,\"line_width\":2,\"line_dash\":[4,4],\"fill_color\":\"lightgrey\",\"fill_alpha\":0.5}}}},{\"type\":\"object\",\"name\":\"SaveTool\",\"id\":\"p1066\"},{\"type\":\"object\",\"name\":\"ResetTool\",\"id\":\"p1067\"},{\"type\":\"object\",\"name\":\"HelpTool\",\"id\":\"p1068\"}]}},\"left\":[{\"type\":\"object\",\"name\":\"LinearAxis\",\"id\":\"p1057\",\"attributes\":{\"ticker\":{\"type\":\"object\",\"name\":\"BasicTicker\",\"id\":\"p1058\",\"attributes\":{\"mantissas\":[1,2,5]}},\"formatter\":{\"type\":\"object\",\"name\":\"BasicTickFormatter\",\"id\":\"p1059\"},\"axis_label\":\"average percent correct\",\"major_label_policy\":{\"type\":\"object\",\"name\":\"AllLabels\",\"id\":\"p1060\"}}}],\"below\":[{\"type\":\"object\",\"name\":\"CategoricalAxis\",\"id\":\"p1052\",\"attributes\":{\"ticker\":{\"type\":\"object\",\"name\":\"CategoricalTicker\",\"id\":\"p1053\"},\"formatter\":{\"type\":\"object\",\"name\":\"CategoricalTickFormatter\",\"id\":\"p1054\"},\"major_label_policy\":{\"type\":\"object\",\"name\":\"AllLabels\",\"id\":\"p1055\"}}}],\"center\":[{\"type\":\"object\",\"name\":\"Grid\",\"id\":\"p1056\",\"attributes\":{\"axis\":{\"id\":\"p1052\"},\"grid_line_color\":null}},{\"type\":\"object\",\"name\":\"Grid\",\"id\":\"p1061\",\"attributes\":{\"dimension\":1,\"axis\":{\"id\":\"p1057\"}}}]}}]}};\n", " const render_items = [{\"docid\":\"f34f9bde-1da9-4dae-b9d2-3c97437b5a51\",\"roots\":{\"p1039\":\"af6bcc3b-bf34-48d1-afa5-844acc412cfb\"},\"root_ids\":[\"p1039\"]}];\n", " root.Bokeh.embed.embed_items_notebook(docs_json, render_items);\n", " }\n", " if (root.Bokeh !== undefined) {\n", " embed_document(root);\n", " } else {\n", " let attempts = 0;\n", " const timer = setInterval(function(root) {\n", " if (root.Bokeh !== undefined) {\n", " clearInterval(timer);\n", " embed_document(root);\n", " } else {\n", " attempts++;\n", " if (attempts > 100) {\n", " clearInterval(timer);\n", " console.log(\"Bokeh: ERROR: Unable to run BokehJS code because BokehJS library is missing\");\n", " }\n", " }\n", " }, 10, root)\n", " }\n", "})(window);" ], "application/vnd.bokehjs_exec.v0+json": "" }, "metadata": { "application/vnd.bokehjs_exec.v0+json": { "id": "p1039" } }, "output_type": "display_data" } ], "source": [ "p = bokeh.plotting.figure(\n", " height=250,\n", " width=250,\n", " x_range=df_mean[\"sleeper\"].unique()[::-1],\n", " y_range=[0, 100],\n", " y_axis_label=\"average percent correct\",\n", ")\n", "\n", "p.vbar(\n", " source=df_mean,\n", " x=\"sleeper\",\n", " top=\"percent correct\",\n", " width=0.6,\n", ")\n", "\n", "p.xgrid.grid_line_color = None\n", "\n", "bokeh.io.show(p)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Nested categorical axes\n", "\n", "We may wish to make a bar graph where we have four bars, normal and insomniac for males and also normal and insomniac for females. To start, we will have to re-make the `df_mean` data frame, now grouping by gender and sleeper. Furthermore, it will be nicer to label the categories as \"female\" and \"male\" instead of \"f\" and \"m\"." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
gendersleeperpercent correct
0femaleinsomniac73.947368
1femalenormal82.045455
2maleinsomniac82.916667
3malenormal80.000000
\n", "
" ], "text/plain": [ " gender sleeper percent correct\n", "0 female insomniac 73.947368\n", "1 female normal 82.045455\n", "2 male insomniac 82.916667\n", "3 male normal 80.000000" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df[\"gender\"] = df[\"gender\"].apply(lambda x: \"female\" if x == \"f\" else \"male\")\n", "\n", "df_mean = df.groupby([\"gender\", \"sleeper\"])[\"percent correct\"].mean().reset_index()\n", "\n", "# Take a look\n", "df_mean" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Because of the way Bokeh handles nested categories, we need to create a new column that has a tuple corresponding to the nested category. To make the tuple, we can again apply a function, this time to each entire row of the data frame (which requires the `axis=1` kwarg of `df_mean.apply()`)." ] }, { "cell_type": "code", "execution_count": 10, "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", "
gendersleeperpercent correctcats
0femaleinsomniac73.947368(female, insomniac)
1femalenormal82.045455(female, normal)
2maleinsomniac82.916667(male, insomniac)
3malenormal80.000000(male, normal)
\n", "
" ], "text/plain": [ " gender sleeper percent correct cats\n", "0 female insomniac 73.947368 (female, insomniac)\n", "1 female normal 82.045455 (female, normal)\n", "2 male insomniac 82.916667 (male, insomniac)\n", "3 male normal 80.000000 (male, normal)" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df_mean[\"cats\"] = df_mean.apply(lambda x: (x[\"gender\"], x[\"sleeper\"]), axis=1)\n", "\n", "# Take a look\n", "df_mean" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next, we need to set up **factors**, which give the nested categories. We could extract them from the `'cats'` column of the data frame as\n", "\n", "```python\n", "factors = list(df_mean.cats)\n", "```\n", "\n", "Instead, we will specify them by hand to ensure they are ordered as we would like." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "factors = [\n", " (\"female\", \"normal\"),\n", " (\"female\", \"insomniac\"),\n", " (\"male\", \"normal\"),\n", " (\"male\", \"insomniac\"),\n", "]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, to use these factors in a `y_range` (or `x_range`), we need to convert them to a **factor range** using `bokeh.models.FactorRange()`." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "p = bokeh.plotting.figure(\n", " height=200,\n", " width=400,\n", " x_axis_label=\"average percent correct\",\n", " x_range=[0, 100],\n", " y_range=bokeh.models.FactorRange(*factors),\n", " tools=\"save\",\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we are ready to add the bars, taking care to specify the `'cats'` column for our y-values." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "
\n" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/javascript": [ "(function(root) {\n", " function embed_document(root) {\n", " const docs_json = {\"86eabef4-4634-483f-9546-f605494ada60\":{\"version\":\"3.2.1\",\"title\":\"Bokeh Application\",\"roots\":[{\"type\":\"object\",\"name\":\"Figure\",\"id\":\"p1084\",\"attributes\":{\"width\":400,\"height\":200,\"x_range\":{\"type\":\"object\",\"name\":\"Range1d\",\"id\":\"p1093\",\"attributes\":{\"end\":100}},\"y_range\":{\"type\":\"object\",\"name\":\"FactorRange\",\"id\":\"p1083\",\"attributes\":{\"factors\":[[\"female\",\"normal\"],[\"female\",\"insomniac\"],[\"male\",\"normal\"],[\"male\",\"insomniac\"]]}},\"x_scale\":{\"type\":\"object\",\"name\":\"LinearScale\",\"id\":\"p1094\"},\"y_scale\":{\"type\":\"object\",\"name\":\"CategoricalScale\",\"id\":\"p1095\"},\"title\":{\"type\":\"object\",\"name\":\"Title\",\"id\":\"p1091\"},\"renderers\":[{\"type\":\"object\",\"name\":\"GlyphRenderer\",\"id\":\"p1116\",\"attributes\":{\"data_source\":{\"type\":\"object\",\"name\":\"ColumnDataSource\",\"id\":\"p1107\",\"attributes\":{\"selected\":{\"type\":\"object\",\"name\":\"Selection\",\"id\":\"p1108\",\"attributes\":{\"indices\":[],\"line_indices\":[]}},\"selection_policy\":{\"type\":\"object\",\"name\":\"UnionRenderers\",\"id\":\"p1109\"},\"data\":{\"type\":\"map\",\"entries\":[[\"index\",{\"type\":\"ndarray\",\"array\":{\"type\":\"bytes\",\"data\":\"AAAAAAEAAAACAAAAAwAAAA==\"},\"shape\":[4],\"dtype\":\"int32\",\"order\":\"little\"}],[\"gender\",{\"type\":\"ndarray\",\"array\":[\"female\",\"female\",\"male\",\"male\"],\"shape\":[4],\"dtype\":\"object\",\"order\":\"little\"}],[\"sleeper\",{\"type\":\"ndarray\",\"array\":[\"insomniac\",\"normal\",\"insomniac\",\"normal\"],\"shape\":[4],\"dtype\":\"object\",\"order\":\"little\"}],[\"percent correct\",{\"type\":\"ndarray\",\"array\":{\"type\":\"bytes\",\"data\":\"ymsor6F8UkCjiy666IJUQKuqqqqqulRAAAAAAAAAVEA=\"},\"shape\":[4],\"dtype\":\"float64\",\"order\":\"little\"}],[\"cats\",{\"type\":\"ndarray\",\"array\":[[\"female\",\"insomniac\"],[\"female\",\"normal\"],[\"male\",\"insomniac\"],[\"male\",\"normal\"]],\"shape\":[4],\"dtype\":\"object\",\"order\":\"little\"}]]}}},\"view\":{\"type\":\"object\",\"name\":\"CDSView\",\"id\":\"p1117\",\"attributes\":{\"filter\":{\"type\":\"object\",\"name\":\"AllIndices\",\"id\":\"p1118\"}}},\"glyph\":{\"type\":\"object\",\"name\":\"HBar\",\"id\":\"p1113\",\"attributes\":{\"y\":{\"type\":\"field\",\"field\":\"cats\"},\"height\":{\"type\":\"value\",\"value\":0.6},\"right\":{\"type\":\"field\",\"field\":\"percent correct\"},\"line_color\":{\"type\":\"value\",\"value\":\"#1f77b4\"},\"fill_color\":{\"type\":\"value\",\"value\":\"#1f77b4\"}}},\"nonselection_glyph\":{\"type\":\"object\",\"name\":\"HBar\",\"id\":\"p1114\",\"attributes\":{\"y\":{\"type\":\"field\",\"field\":\"cats\"},\"height\":{\"type\":\"value\",\"value\":0.6},\"right\":{\"type\":\"field\",\"field\":\"percent correct\"},\"line_color\":{\"type\":\"value\",\"value\":\"#1f77b4\"},\"line_alpha\":{\"type\":\"value\",\"value\":0.1},\"fill_color\":{\"type\":\"value\",\"value\":\"#1f77b4\"},\"fill_alpha\":{\"type\":\"value\",\"value\":0.1},\"hatch_alpha\":{\"type\":\"value\",\"value\":0.1}}},\"muted_glyph\":{\"type\":\"object\",\"name\":\"HBar\",\"id\":\"p1115\",\"attributes\":{\"y\":{\"type\":\"field\",\"field\":\"cats\"},\"height\":{\"type\":\"value\",\"value\":0.6},\"right\":{\"type\":\"field\",\"field\":\"percent correct\"},\"line_color\":{\"type\":\"value\",\"value\":\"#1f77b4\"},\"line_alpha\":{\"type\":\"value\",\"value\":0.2},\"fill_color\":{\"type\":\"value\",\"value\":\"#1f77b4\"},\"fill_alpha\":{\"type\":\"value\",\"value\":0.2},\"hatch_alpha\":{\"type\":\"value\",\"value\":0.2}}}}}],\"toolbar\":{\"type\":\"object\",\"name\":\"Toolbar\",\"id\":\"p1092\",\"attributes\":{\"tools\":[{\"type\":\"object\",\"name\":\"SaveTool\",\"id\":\"p1106\"}]}},\"left\":[{\"type\":\"object\",\"name\":\"CategoricalAxis\",\"id\":\"p1101\",\"attributes\":{\"ticker\":{\"type\":\"object\",\"name\":\"CategoricalTicker\",\"id\":\"p1102\"},\"formatter\":{\"type\":\"object\",\"name\":\"CategoricalTickFormatter\",\"id\":\"p1103\"},\"major_label_policy\":{\"type\":\"object\",\"name\":\"AllLabels\",\"id\":\"p1104\"}}}],\"below\":[{\"type\":\"object\",\"name\":\"LinearAxis\",\"id\":\"p1096\",\"attributes\":{\"ticker\":{\"type\":\"object\",\"name\":\"BasicTicker\",\"id\":\"p1097\",\"attributes\":{\"mantissas\":[1,2,5]}},\"formatter\":{\"type\":\"object\",\"name\":\"BasicTickFormatter\",\"id\":\"p1098\"},\"axis_label\":\"average percent correct\",\"major_label_policy\":{\"type\":\"object\",\"name\":\"AllLabels\",\"id\":\"p1099\"}}}],\"center\":[{\"type\":\"object\",\"name\":\"Grid\",\"id\":\"p1100\",\"attributes\":{\"axis\":{\"id\":\"p1096\"}}},{\"type\":\"object\",\"name\":\"Grid\",\"id\":\"p1105\",\"attributes\":{\"dimension\":1,\"axis\":{\"id\":\"p1101\"},\"grid_line_color\":null}}]}}]}};\n", " const render_items = [{\"docid\":\"86eabef4-4634-483f-9546-f605494ada60\",\"roots\":{\"p1084\":\"b98e56dd-b470-4145-9123-cb192927fe33\"},\"root_ids\":[\"p1084\"]}];\n", " root.Bokeh.embed.embed_items_notebook(docs_json, render_items);\n", " }\n", " if (root.Bokeh !== undefined) {\n", " embed_document(root);\n", " } else {\n", " let attempts = 0;\n", " const timer = setInterval(function(root) {\n", " if (root.Bokeh !== undefined) {\n", " clearInterval(timer);\n", " embed_document(root);\n", " } else {\n", " attempts++;\n", " if (attempts > 100) {\n", " clearInterval(timer);\n", " console.log(\"Bokeh: ERROR: Unable to run BokehJS code because BokehJS library is missing\");\n", " }\n", " }\n", " }, 10, root)\n", " }\n", "})(window);" ], "application/vnd.bokehjs_exec.v0+json": "" }, "metadata": { "application/vnd.bokehjs_exec.v0+json": { "id": "p1084" } }, "output_type": "display_data" } ], "source": [ "p.hbar(\n", " source=df_mean,\n", " y=\"cats\",\n", " right=\"percent correct\",\n", " height=0.6,\n", ")\n", "\n", "p.ygrid.grid_line_color = None\n", "\n", "bokeh.io.show(p)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Computing environment" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Python implementation: CPython\n", "Python version : 3.11.5\n", "IPython version : 8.15.0\n", "\n", "pandas : 2.0.3\n", "bokeh : 3.2.1\n", "jupyterlab: 4.0.6\n", "\n" ] } ], "source": [ "%load_ext watermark\n", "%watermark -v -p pandas,bokeh,jupyterlab" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.5" } }, "nbformat": 4, "nbformat_minor": 4 }