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

Bokeh Tutorial

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

08. Graph and Network Plots

" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This chapter will cover how to plot network node/link graphs in Bokeh using NetwortkX. For information on creating graph renderers from a low level, see [Visualizing Network Graphs](https://docs.bokeh.org/en/latest/docs/user_guide/graph.html)\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\") || (!output.data.hasOwnProperty(EXEC_MIME_TYPE))) {\n", " return\n", " }\n", "\n", " var toinsert = output_area.element.find(\".\" + CLASS_NAME.split(' ')[0]);\n", "\n", " if (output.metadata[EXEC_MIME_TYPE][\"id\"] !== undefined) {\n", " toinsert[toinsert.length - 1].firstChild.textContent = output.data[JS_MIME_TYPE];\n", " // store reference to embed id on output_area\n", " output_area._bokeh_element_id = output.metadata[EXEC_MIME_TYPE][\"id\"];\n", " }\n", " if (output.metadata[EXEC_MIME_TYPE][\"server_id\"] !== undefined) {\n", " var bk_div = document.createElement(\"div\");\n", " bk_div.innerHTML = output.data[HTML_MIME_TYPE];\n", " var script_attrs = bk_div.children[0].attributes;\n", " for (var i = 0; i < script_attrs.length; i++) {\n", " toinsert[toinsert.length - 1].firstChild.setAttribute(script_attrs[i].name, script_attrs[i].value);\n", " toinsert[toinsert.length - 1].firstChild.textContent = bk_div.children[0].textContent\n", " }\n", " // store reference to server id on output_area\n", " output_area._bokeh_server_id = output.metadata[EXEC_MIME_TYPE][\"server_id\"];\n", " }\n", " }\n", "\n", " function register_renderer(events, OutputArea) {\n", "\n", " function append_mime(data, metadata, element) {\n", " // create a DOM node to render to\n", " var toinsert = this.create_output_subarea(\n", " metadata,\n", " CLASS_NAME,\n", " EXEC_MIME_TYPE\n", " );\n", " this.keyboard_manager.register_events(toinsert);\n", " // Render to node\n", " var props = {data: data, metadata: metadata[EXEC_MIME_TYPE]};\n", " render(props, toinsert[toinsert.length - 1]);\n", " element.append(toinsert);\n", " return toinsert\n", " }\n", "\n", " /* Handle when an output is cleared or removed */\n", " events.on('clear_output.CodeCell', handleClearOutput);\n", " events.on('delete.Cell', handleClearOutput);\n", "\n", " /* Handle when a new output is added */\n", " events.on('output_added.OutputArea', handleAddOutput);\n", "\n", " /**\n", " * Register the mime type and append_mime function with output_area\n", " */\n", " OutputArea.prototype.register_mime_type(EXEC_MIME_TYPE, append_mime, {\n", " /* Is output safe? */\n", " safe: true,\n", " /* Index of renderer in `output_area.display_order` */\n", " index: 0\n", " });\n", " }\n", "\n", " // register the mime type if in Jupyter Notebook environment and previously unregistered\n", " if (root.Jupyter !== undefined) {\n", " var events = require('base/js/events');\n", " var OutputArea = require('notebook/js/outputarea').OutputArea;\n", "\n", " if (OutputArea.prototype.mime_types().indexOf(EXEC_MIME_TYPE) == -1) {\n", " register_renderer(events, OutputArea);\n", " }\n", " }\n", "\n", " \n", " if (typeof (root._bokeh_timeout) === \"undefined\" || force === true) {\n", " root._bokeh_timeout = Date.now() + 5000;\n", " root._bokeh_failed_load = false;\n", " }\n", "\n", " var NB_LOAD_WARNING = {'data': {'text/html':\n", " \"
\\n\"+\n", " \"

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

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

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

\\n\"+\n \"\\n\"+\n \"\\n\"+\n \"from bokeh.resources import INLINE\\n\"+\n \"output_notebook(resources=INLINE)\\n\"+\n \"\\n\"+\n \"
\"}};\n\n function display_loaded() {\n var el = document.getElementById(\"1001\");\n if (el != null) {\n el.textContent = \"BokehJS is loading...\";\n }\n if (root.Bokeh !== undefined) {\n if (el != null) {\n el.textContent = \"BokehJS \" + root.Bokeh.version + \" successfully loaded.\";\n }\n } else if (Date.now() < root._bokeh_timeout) {\n setTimeout(display_loaded, 100)\n }\n }\n\n\n function run_callbacks() {\n try {\n root._bokeh_onload_callbacks.forEach(function(callback) {\n if (callback != null)\n callback();\n });\n } finally {\n delete root._bokeh_onload_callbacks\n }\n console.debug(\"Bokeh: all callbacks have finished\");\n }\n\n function load_libs(css_urls, js_urls, callback) {\n if (css_urls == null) css_urls = [];\n if (js_urls == null) js_urls = [];\n\n root._bokeh_onload_callbacks.push(callback);\n if (root._bokeh_is_loading > 0) {\n console.debug(\"Bokeh: BokehJS is being loaded, scheduling callback at\", now());\n return null;\n }\n if (js_urls == null || js_urls.length === 0) {\n run_callbacks();\n return null;\n }\n console.debug(\"Bokeh: BokehJS not loaded, scheduling load and callback at\", now());\n root._bokeh_is_loading = css_urls.length + js_urls.length;\n\n function on_load() {\n root._bokeh_is_loading--;\n if (root._bokeh_is_loading === 0) {\n console.debug(\"Bokeh: all BokehJS libraries/stylesheets loaded\");\n run_callbacks()\n }\n }\n\n function on_error() {\n console.error(\"failed to load \" + url);\n }\n\n for (var i = 0; i < css_urls.length; i++) {\n var url = css_urls[i];\n const element = document.createElement(\"link\");\n element.onload = on_load;\n element.onerror = on_error;\n element.rel = \"stylesheet\";\n element.type = \"text/css\";\n element.href = url;\n console.debug(\"Bokeh: injecting link tag for BokehJS stylesheet: \", url);\n document.body.appendChild(element);\n }\n\n const hashes = {\"https://cdn.bokeh.org/bokeh/release/bokeh-2.0.1.min.js\": \"JpP8FXbgAZLkfur7LiK3j9AGBhHNIvF742meBJrjO2ShJDhCG2I1uVvW+0DUtrmc\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.0.1.min.js\": \"xZlADit0Q04ISQEdKg2k3L4W9AwQBAuDs9nJL9fM/WwzL1tEU9VPNezOFX0nLEAz\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.0.1.min.js\": \"4BuPRZkdMKSnj3zoxiNrQ86XgNw0rYmBOxe7nshquXwwcauupgBF2DHLVG1WuZlV\", \"https://cdn.bokeh.org/bokeh/release/bokeh-gl-2.0.1.min.js\": \"Dv1SQ87hmDqK6S5OhBf0bCuwAEvL5QYL0PuR/F1SPVhCS/r/abjkbpKDYL2zeM19\"};\n\n for (var i = 0; i < js_urls.length; i++) {\n var url = js_urls[i];\n var element = document.createElement('script');\n element.onload = on_load;\n element.onerror = on_error;\n element.async = false;\n element.src = url;\n if (url in hashes) {\n element.crossOrigin = \"anonymous\";\n element.integrity = \"sha384-\" + hashes[url];\n }\n console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n document.head.appendChild(element);\n }\n };var element = document.getElementById(\"1001\");\n if (element == null) {\n console.error(\"Bokeh: ERROR: autoload.js configured with elementid '1001' but no matching script tag was found. \")\n return false;\n }\n\n function inject_raw_css(css) {\n const element = document.createElement(\"style\");\n element.appendChild(document.createTextNode(css));\n document.body.appendChild(element);\n }\n\n \n var js_urls = [\"https://cdn.bokeh.org/bokeh/release/bokeh-2.0.1.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.0.1.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.0.1.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-gl-2.0.1.min.js\"];\n var css_urls = [];\n \n\n var inline_js = [\n function(Bokeh) {\n Bokeh.set_log_level(\"info\");\n },\n function(Bokeh) {\n \n \n }\n ];\n\n function run_inline_js() {\n \n if (root.Bokeh !== undefined || force === true) {\n \n for (var i = 0; i < inline_js.length; i++) {\n inline_js[i].call(root, root.Bokeh);\n }\n if (force === true) {\n display_loaded();\n }} else if (Date.now() < root._bokeh_timeout) {\n setTimeout(run_inline_js, 100);\n } else if (!root._bokeh_failed_load) {\n console.log(\"Bokeh: BokehJS failed to load within specified timeout.\");\n root._bokeh_failed_load = true;\n } else if (force !== true) {\n var cell = $(document.getElementById(\"1001\")).parents('.cell').data().cell;\n cell.output_area.append_execute_result(NB_LOAD_WARNING)\n }\n\n }\n\n if (root._bokeh_is_loading === 0) {\n console.debug(\"Bokeh: BokehJS loaded, going straight to plotting\");\n run_inline_js();\n } else {\n load_libs(css_urls, js_urls, function() {\n console.debug(\"Bokeh: BokehJS plotting callback run at\", now());\n run_inline_js();\n });\n }\n}(window));" }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from bokeh.io import show, output_notebook\n", "from bokeh.plotting import figure\n", "\n", "output_notebook()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Plotting from NetworkX\n", "\n", "The easiest way to plot network graphs with Bokeh is to use the `from_networkx` function. This function accepts any NetworkX graph and returns a Bokeh `GraphRenderer` that can be added to a plot. The `GraphRenderer` has `node_renderer` and `edge_renderer` properties that contain the Bokeh renderers that draw the nodes and edges, respectively. \n", "\n", "The example below shows a Bokeh plot of `nx.desargues_graph()`, setting some of the node and edge properties." ] }, { "cell_type": "code", "execution_count": 2, "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 = {\"d4dbe452-03f6-4209-8bc7-57d2c5e76be5\":{\"roots\":{\"references\":[{\"attributes\":{\"renderers\":[{\"id\":\"1007\"}],\"title\":{\"id\":\"1026\"},\"toolbar\":{\"id\":\"1028\"},\"x_range\":{\"id\":\"1002\"},\"x_scale\":{\"id\":\"1025\"},\"y_range\":{\"id\":\"1003\"},\"y_scale\":{\"id\":\"1027\"}},\"id\":\"1004\",\"type\":\"Plot\"},{\"attributes\":{},\"id\":\"1042\",\"type\":\"Selection\"},{\"attributes\":{},\"id\":\"1041\",\"type\":\"UnionRenderers\"},{\"attributes\":{},\"id\":\"1025\",\"type\":\"LinearScale\"},{\"attributes\":{},\"id\":\"1029\",\"type\":\"NodesOnly\"},{\"attributes\":{\"end\":2,\"start\":-2},\"id\":\"1003\",\"type\":\"Range1d\"},{\"attributes\":{\"end\":2,\"start\":-2},\"id\":\"1002\",\"type\":\"Range1d\"},{\"attributes\":{},\"id\":\"1027\",\"type\":\"LinearScale\"},{\"attributes\":{},\"id\":\"1038\",\"type\":\"NodesOnly\"},{\"attributes\":{\"data\":{\"end\":[1,19,5,2,16,3,11,4,14,5,9,6,7,15,8,18,9,13,10,11,19,12,13,17,14,15,16,17,18,19],\"start\":[0,0,0,1,1,2,2,3,3,4,4,5,6,6,7,7,8,8,9,10,10,11,12,12,13,14,15,16,17,18]},\"selected\":{\"id\":\"1040\"},\"selection_policy\":{\"id\":\"1039\"}},\"id\":\"1013\",\"type\":\"ColumnDataSource\"},{\"attributes\":{\"data_source\":{\"id\":\"1013\"},\"glyph\":{\"id\":\"1012\"},\"hover_glyph\":null,\"muted_glyph\":null,\"view\":{\"id\":\"1015\"}},\"id\":\"1014\",\"type\":\"GlyphRenderer\"},{\"attributes\":{\"fill_color\":{\"value\":\"orange\"},\"size\":{\"units\":\"screen\",\"value\":20}},\"id\":\"1008\",\"type\":\"Circle\"},{\"attributes\":{\"line_dash\":[2,2]},\"id\":\"1012\",\"type\":\"MultiLine\"},{\"attributes\":{\"graph_layout\":{\"0\":[-1.1042342270583827,-1.1358203033156933],\"1\":[-0.32528538882698,-1.7994753213588925],\"10\":[-1.625670493253707,0.8619054556698852],\"11\":[-0.9937202605143635,0.18131834718760223],\"12\":[0.22787948925992138,0.36722672691041464],\"13\":[1.1168440806216449,1.1183473694056227],\"14\":[1.6157242120675364,0.1547889930386424],\"15\":[1.61261258064872,-0.8611365542446111],\"16\":[0.7754992820567755,-1.6394034299170748],\"17\":[0.3146902597398338,-0.7525670875693947],\"18\":[-0.49184158969092406,0.06231601538197338],\"19\":[-1.616014837453719,-0.17249304477551114],\"2\":[-0.4659406014608107,-0.8636140545286619],\"3\":[0.4815995343541902,-0.0836919751599053],\"4\":[-0.31234089232066437,0.7291976828651057],\"5\":[-0.19796639546974296,-0.3605636780163431],\"6\":[0.9946709677016442,-0.11662921985543172],\"7\":[0.4435326518309118,0.8939251155381592],\"8\":[0.3302811789520167,1.8],\"9\":[-0.7803195511838985,1.6163689627441111]}},\"id\":\"1016\",\"type\":\"StaticLayoutProvider\"},{\"attributes\":{\"data\":{\"index\":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]},\"selected\":{\"id\":\"1042\"},\"selection_policy\":{\"id\":\"1041\"}},\"id\":\"1009\",\"type\":\"ColumnDataSource\"},{\"attributes\":{\"source\":{\"id\":\"1009\"}},\"id\":\"1011\",\"type\":\"CDSView\"},{\"attributes\":{\"source\":{\"id\":\"1013\"}},\"id\":\"1015\",\"type\":\"CDSView\"},{\"attributes\":{\"text\":\"\"},\"id\":\"1026\",\"type\":\"Title\"},{\"attributes\":{\"edge_renderer\":{\"id\":\"1014\"},\"inspection_policy\":{\"id\":\"1029\"},\"layout_provider\":{\"id\":\"1016\"},\"node_renderer\":{\"id\":\"1010\"},\"selection_policy\":{\"id\":\"1038\"}},\"id\":\"1007\",\"type\":\"GraphRenderer\"},{\"attributes\":{},\"id\":\"1039\",\"type\":\"UnionRenderers\"},{\"attributes\":{\"active_drag\":\"auto\",\"active_inspect\":\"auto\",\"active_multi\":null,\"active_scroll\":\"auto\",\"active_tap\":\"auto\"},\"id\":\"1028\",\"type\":\"Toolbar\"},{\"attributes\":{},\"id\":\"1040\",\"type\":\"Selection\"},{\"attributes\":{\"data_source\":{\"id\":\"1009\"},\"glyph\":{\"id\":\"1008\"},\"hover_glyph\":null,\"muted_glyph\":null,\"view\":{\"id\":\"1011\"}},\"id\":\"1010\",\"type\":\"GlyphRenderer\"}],\"root_ids\":[\"1004\"]},\"title\":\"Bokeh Application\",\"version\":\"2.0.1\"}};\n", " var render_items = [{\"docid\":\"d4dbe452-03f6-4209-8bc7-57d2c5e76be5\",\"root_ids\":[\"1004\"],\"roots\":{\"1004\":\"287e2448-5aa8-4de4-879b-11b6f8280e46\"}}];\n", " root.Bokeh.embed.embed_items_notebook(docs_json, render_items);\n", "\n", " }\n", " if (root.Bokeh !== undefined) {\n", " embed_document(root);\n", " } else {\n", " var attempts = 0;\n", " var timer = setInterval(function(root) {\n", " if (root.Bokeh !== undefined) {\n", " clearInterval(timer);\n", " embed_document(root);\n", " } else {\n", " attempts++;\n", " if (attempts > 100) {\n", " clearInterval(timer);\n", " console.log(\"Bokeh: ERROR: Unable to run BokehJS code because BokehJS library is missing\");\n", " }\n", " }\n", " }, 10, root)\n", " }\n", "})(window);" ], "application/vnd.bokehjs_exec.v0+json": "" }, "metadata": { "application/vnd.bokehjs_exec.v0+json": { "id": "1004" } }, "output_type": "display_data" } ], "source": [ "import networkx as nx\n", "from bokeh.models import Range1d, Plot\n", "from bokeh.plotting import from_networkx\n", "\n", "G = nx.desargues_graph()\n", "\n", "# We could use figure here but don't want all the axes and titles\n", "plot = Plot(x_range=Range1d(-2, 2), y_range=Range1d(-2, 2))\n", "\n", "# Create a Bokeh graph from the NetworkX input using nx.spring_layout\n", "graph = from_networkx(G, nx.spring_layout, scale=1.8, center=(0,0))\n", "plot.renderers.append(graph)\n", "\n", "# Set some of the default node glyph (Circle) properties\n", "graph.node_renderer.glyph.update(size=20, fill_color=\"orange\")\n", "\n", "# Set some edge properties too\n", "graph.edge_renderer.glyph.line_dash = [2,2]\n", "\n", "show(plot)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "# Exercise: try a different NetworkX layout, and set some properies on `graph.edge_renderer.glyph` \n", "# and `graph.node_renderer.glyph`\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Adding Extra Data Columns.\n", "\n", "The `node_renderer` and `edge_renderer` properties of the graph renderer each have a `data_source` that is a standard `ColumnDataSource` that you can add new data to, e.g. to drive a hover tool, or to specify colors for the renderer. The example below demonstates both." ] }, { "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 = {\"e8d65793-b5c5-4264-a983-2cf19d800507\":{\"roots\":{\"references\":[{\"attributes\":{\"renderers\":[{\"id\":\"1176\"}],\"title\":{\"id\":\"1219\"},\"toolbar\":{\"id\":\"1199\"},\"x_range\":{\"id\":\"1171\"},\"x_scale\":{\"id\":\"1218\"},\"y_range\":{\"id\":\"1172\"},\"y_scale\":{\"id\":\"1220\"}},\"id\":\"1173\",\"type\":\"Plot\"},{\"attributes\":{\"data_source\":{\"id\":\"1182\"},\"glyph\":{\"id\":\"1181\"},\"hover_glyph\":null,\"muted_glyph\":null,\"view\":{\"id\":\"1184\"}},\"id\":\"1183\",\"type\":\"GlyphRenderer\"},{\"attributes\":{\"fill_color\":{\"field\":\"colors\"},\"size\":{\"units\":\"screen\",\"value\":20}},\"id\":\"1177\",\"type\":\"Circle\"},{\"attributes\":{},\"id\":\"1218\",\"type\":\"LinearScale\"},{\"attributes\":{\"edge_renderer\":{\"id\":\"1183\"},\"inspection_policy\":{\"id\":\"1222\"},\"layout_provider\":{\"id\":\"1185\"},\"node_renderer\":{\"id\":\"1179\"},\"selection_policy\":{\"id\":\"1231\"}},\"id\":\"1176\",\"type\":\"GraphRenderer\"},{\"attributes\":{},\"id\":\"1234\",\"type\":\"UnionRenderers\"},{\"attributes\":{},\"id\":\"1235\",\"type\":\"Selection\"},{\"attributes\":{},\"id\":\"1220\",\"type\":\"LinearScale\"},{\"attributes\":{\"text\":\"\"},\"id\":\"1219\",\"type\":\"Title\"},{\"attributes\":{},\"id\":\"1222\",\"type\":\"NodesOnly\"},{\"attributes\":{\"data\":{\"end\":[1,19,5,2,16,3,11,4,14,5,9,6,7,15,8,18,9,13,10,11,19,12,13,17,14,15,16,17,18,19],\"start\":[0,0,0,1,1,2,2,3,3,4,4,5,6,6,7,7,8,8,9,10,10,11,12,12,13,14,15,16,17,18]},\"selected\":{\"id\":\"1233\"},\"selection_policy\":{\"id\":\"1232\"}},\"id\":\"1182\",\"type\":\"ColumnDataSource\"},{\"attributes\":{},\"id\":\"1231\",\"type\":\"NodesOnly\"},{\"attributes\":{\"callback\":null,\"tooltips\":\"index: @index\"},\"id\":\"1198\",\"type\":\"HoverTool\"},{\"attributes\":{\"data_source\":{\"id\":\"1178\"},\"glyph\":{\"id\":\"1177\"},\"hover_glyph\":null,\"muted_glyph\":null,\"view\":{\"id\":\"1180\"}},\"id\":\"1179\",\"type\":\"GlyphRenderer\"},{\"attributes\":{\"end\":2,\"start\":-2},\"id\":\"1171\",\"type\":\"Range1d\"},{\"attributes\":{\"data\":{\"colors\":[\"#1f77b4\",\"#aec7e8\",\"#ff7f0e\",\"#ffbb78\",\"#2ca02c\",\"#98df8a\",\"#d62728\",\"#ff9896\",\"#9467bd\",\"#c5b0d5\",\"#8c564b\",\"#c49c94\",\"#e377c2\",\"#f7b6d2\",\"#7f7f7f\",\"#c7c7c7\",\"#bcbd22\",\"#dbdb8d\",\"#17becf\",\"#9edae5\"],\"index\":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]},\"selected\":{\"id\":\"1235\"},\"selection_policy\":{\"id\":\"1234\"}},\"id\":\"1178\",\"type\":\"ColumnDataSource\"},{\"attributes\":{\"end\":2,\"start\":-2},\"id\":\"1172\",\"type\":\"Range1d\"},{\"attributes\":{\"source\":{\"id\":\"1178\"}},\"id\":\"1180\",\"type\":\"CDSView\"},{\"attributes\":{\"source\":{\"id\":\"1182\"}},\"id\":\"1184\",\"type\":\"CDSView\"},{\"attributes\":{\"active_drag\":\"auto\",\"active_inspect\":\"auto\",\"active_multi\":null,\"active_scroll\":\"auto\",\"active_tap\":\"auto\",\"tools\":[{\"id\":\"1198\"}]},\"id\":\"1199\",\"type\":\"Toolbar\"},{\"attributes\":{},\"id\":\"1181\",\"type\":\"MultiLine\"},{\"attributes\":{\"graph_layout\":{\"0\":[1.0515968362707657,-1.255341561322923],\"1\":[0.004529336305524424,-1.5528293849193473],\"10\":[0.17700868741796563,0.8835039305391639],\"11\":[-0.9181924731316187,0.5375484026992642],\"12\":[-1.8000000000000003,0.48995537611432627],\"13\":[-1.0534431239036623,1.2598999721436945],\"14\":[-0.3618883739150459,0.37249250484267554],\"15\":[-0.17880110261021936,-0.8896662248563576],\"16\":[-0.9805627702247748,-1.484911991465559],\"17\":[-1.689784752921127,-0.6388597818793655],\"18\":[-0.7331052032293595,-0.3792878309018295],\"19\":[0.3618672511929743,-0.37518842056369683],\"2\":[-0.15904602080640082,-0.3415316511030135],\"3\":[0.7393935700888642,0.3888562655401655],\"4\":[1.693239258433371,0.6504186501218778],\"5\":[1.7999207404597233,-0.4966205304129801],\"6\":[0.9209952330094453,-0.5391817075928242],\"7\":[0.16903182235239397,0.3429042529331822],\"8\":[-0.014912216313250633,1.5415313824254366],\"9\":[0.9721533015244336,1.4863083476581085]}},\"id\":\"1185\",\"type\":\"StaticLayoutProvider\"},{\"attributes\":{},\"id\":\"1232\",\"type\":\"UnionRenderers\"},{\"attributes\":{},\"id\":\"1233\",\"type\":\"Selection\"}],\"root_ids\":[\"1173\"]},\"title\":\"Bokeh Application\",\"version\":\"2.0.1\"}};\n", " var render_items = [{\"docid\":\"e8d65793-b5c5-4264-a983-2cf19d800507\",\"root_ids\":[\"1173\"],\"roots\":{\"1173\":\"896a11db-a60e-4aee-8654-2958666ba64c\"}}];\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": "1173" } }, "output_type": "display_data" } ], "source": [ "from bokeh.models import HoverTool\n", "from bokeh.palettes import Category20_20\n", "\n", "G = nx.desargues_graph() # always 20 nodes\n", "\n", "# We could use figure here but don't want all the axes and titles\n", "plot = Plot(x_range=Range1d(-2, 2), y_range=Range1d(-2, 2))\n", "\n", "# Create a Bokeh graph from the NetworkX input using nx.spring_layout\n", "graph = from_networkx(G, nx.spring_layout, scale=1.8, center=(0,0))\n", "plot.renderers.append(graph)\n", "\n", "# Add some new columns to the node renderer data source\n", "graph.node_renderer.data_source.data['index'] = list(range(len(G)))\n", "graph.node_renderer.data_source.data['colors'] = Category20_20\n", "\n", "graph.node_renderer.glyph.update(size=20, fill_color=\"colors\")\n", "\n", "plot.add_tools(HoverTool(tooltips=\"index: @index\"))\n", "\n", "show(plot)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "# Exercise: Add your own columns for other node or edge properties e.g. fill_alpha or line_color,\n", "# or to show other fields in a tooltoip\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Inspection and Selection Policies\n", "\n", "Bokeh graph renderers have `inspection_policy` and `selection_policy` properties. These can be used to control how hover inspections highlight the graph, or how selection tools make selections. These properties may be set to any of the inpection policies in `bokeh.graphs`. For instance, if a user hovers over a node, you may wish to highlight all the associated edges as well. This can be accomplished by setting the inspection policy:\n", "\n", " graph.inspection_policy = NodesAndLinkedEdges()\n", " \n", "as the example below demonstrates." ] }, { "cell_type": "code", "execution_count": 6, "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 = {\"5f81c02f-15f1-4b90-8138-2bbe70eafff7\":{\"roots\":{\"references\":[{\"attributes\":{\"renderers\":[{\"id\":\"1369\"}],\"title\":{\"id\":\"1440\"},\"toolbar\":{\"id\":\"1402\"},\"x_range\":{\"id\":\"1364\"},\"x_scale\":{\"id\":\"1439\"},\"y_range\":{\"id\":\"1365\"},\"y_scale\":{\"id\":\"1441\"}},\"id\":\"1366\",\"type\":\"Plot\"},{\"attributes\":{},\"id\":\"1453\",\"type\":\"Selection\"},{\"attributes\":{\"data\":{\"end\":[11,7,1,6,3,12,13,11,2,6,10,4,13,12,10,9,12,11,7,8,12,14,12,9,10,8,12,9,13,12],\"start\":[0,0,0,0,0,0,1,1,1,1,2,2,2,3,3,4,4,4,5,5,5,6,6,6,6,7,7,8,10,10]},\"selected\":{\"id\":\"1453\"},\"selection_policy\":{\"id\":\"1452\"}},\"id\":\"1375\",\"type\":\"ColumnDataSource\"},{\"attributes\":{\"line_color\":{\"value\":\"#abdda4\"},\"line_width\":{\"value\":4}},\"id\":\"1394\",\"type\":\"MultiLine\"},{\"attributes\":{\"data\":{\"index\":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]},\"selected\":{\"id\":\"1455\"},\"selection_policy\":{\"id\":\"1454\"}},\"id\":\"1371\",\"type\":\"ColumnDataSource\"},{\"attributes\":{},\"id\":\"1454\",\"type\":\"UnionRenderers\"},{\"attributes\":{},\"id\":\"1455\",\"type\":\"Selection\"},{\"attributes\":{\"source\":{\"id\":\"1371\"}},\"id\":\"1373\",\"type\":\"CDSView\"},{\"attributes\":{},\"id\":\"1451\",\"type\":\"NodesOnly\"},{\"attributes\":{},\"id\":\"1439\",\"type\":\"LinearScale\"},{\"attributes\":{},\"id\":\"1399\",\"type\":\"NodesAndLinkedEdges\"},{\"attributes\":{},\"id\":\"1441\",\"type\":\"LinearScale\"},{\"attributes\":{\"text\":\"\"},\"id\":\"1440\",\"type\":\"Title\"},{\"attributes\":{\"source\":{\"id\":\"1375\"}},\"id\":\"1377\",\"type\":\"CDSView\"},{\"attributes\":{\"fill_color\":{\"value\":\"#2b83ba\"},\"size\":{\"units\":\"screen\",\"value\":25}},\"id\":\"1379\",\"type\":\"Circle\"},{\"attributes\":{\"callback\":null,\"tooltips\":null},\"id\":\"1401\",\"type\":\"HoverTool\"},{\"attributes\":{\"active_drag\":\"auto\",\"active_inspect\":\"auto\",\"active_multi\":null,\"active_scroll\":\"auto\",\"active_tap\":\"auto\",\"tools\":[{\"id\":\"1401\"}]},\"id\":\"1402\",\"type\":\"Toolbar\"},{\"attributes\":{\"data_source\":{\"id\":\"1371\"},\"glyph\":{\"id\":\"1379\"},\"hover_glyph\":{\"id\":\"1389\"},\"muted_glyph\":null,\"view\":{\"id\":\"1373\"}},\"id\":\"1372\",\"type\":\"GlyphRenderer\"},{\"attributes\":{\"line_alpha\":{\"value\":0.8},\"line_color\":{\"value\":\"#cccccc\"},\"line_width\":{\"value\":2}},\"id\":\"1384\",\"type\":\"MultiLine\"},{\"attributes\":{\"edge_renderer\":{\"id\":\"1376\"},\"inspection_policy\":{\"id\":\"1399\"},\"layout_provider\":{\"id\":\"1378\"},\"node_renderer\":{\"id\":\"1372\"},\"selection_policy\":{\"id\":\"1451\"}},\"id\":\"1369\",\"type\":\"GraphRenderer\"},{\"attributes\":{\"data_source\":{\"id\":\"1375\"},\"glyph\":{\"id\":\"1384\"},\"hover_glyph\":{\"id\":\"1394\"},\"muted_glyph\":null,\"view\":{\"id\":\"1377\"}},\"id\":\"1376\",\"type\":\"GlyphRenderer\"},{\"attributes\":{\"fill_color\":{\"value\":\"#abdda4\"},\"size\":{\"units\":\"screen\",\"value\":25}},\"id\":\"1389\",\"type\":\"Circle\"},{\"attributes\":{\"graph_layout\":{\"0\":[-0.07348979989817135,0.05449454682370959],\"1\":[-0.848577117308267,0.8596777277579513],\"10\":[-0.4014927048022815,0.7441272939202426],\"11\":[-1.3659332223311402,-0.06737469580507789],\"12\":[0.45775864306475894,-0.30527024838462435],\"13\":[-1.3390248110427074,1.5782708110302275],\"14\":[1.453304851718345,1.6561750142885403],\"2\":[-1.4996520553360426,0.6782768558445251],\"3\":[-0.35207983735933435,-0.33571282848173944],\"4\":[-0.8643162264938244,-0.6041710223563577],\"5\":[1.6889571287678822,-1.1127840984328077],\"6\":[0.4617452903795823,0.5749544582766315],\"7\":[1.0784954883428057,-0.8570180733106607],\"8\":[1.2905485461482438,-1.8],\"9\":[0.3137558261501579,-1.063645741170558]}},\"id\":\"1378\",\"type\":\"StaticLayoutProvider\"},{\"attributes\":{\"end\":2,\"start\":-2},\"id\":\"1364\",\"type\":\"Range1d\"},{\"attributes\":{\"end\":2,\"start\":-2},\"id\":\"1365\",\"type\":\"Range1d\"},{\"attributes\":{},\"id\":\"1452\",\"type\":\"UnionRenderers\"}],\"root_ids\":[\"1366\"]},\"title\":\"Bokeh Application\",\"version\":\"2.0.1\"}};\n", " var render_items = [{\"docid\":\"5f81c02f-15f1-4b90-8138-2bbe70eafff7\",\"root_ids\":[\"1366\"],\"roots\":{\"1366\":\"2638454e-062e-41a6-a49d-f5b673f87110\"}}];\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": "1366" } }, "output_type": "display_data" } ], "source": [ "from bokeh.models.graphs import NodesAndLinkedEdges\n", "from bokeh.models import Circle, HoverTool, MultiLine\n", "\n", "G = nx.gnm_random_graph(15, 30)\n", "\n", "# We could use figure here but don't want all the axes and titles\n", "plot = Plot(x_range=Range1d(-2, 2), y_range=Range1d(-2 ,2))\n", "\n", "# Create a Bokeh graph from the NetworkX input using nx.spring_layout\n", "graph = from_networkx(G, nx.spring_layout, scale=1.8, center=(0,0))\n", "plot.renderers.append(graph)\n", "\n", "# Blue circles for nodes, and light grey lines for edges\n", "graph.node_renderer.glyph = Circle(size=25, fill_color='#2b83ba')\n", "graph.edge_renderer.glyph = MultiLine(line_color=\"#cccccc\", line_alpha=0.8, line_width=2)\n", "\n", "# green hover for both nodes and edges\n", "graph.node_renderer.hover_glyph = Circle(size=25, fill_color='#abdda4')\n", "graph.edge_renderer.hover_glyph = MultiLine(line_color='#abdda4', line_width=4)\n", "\n", "# When we hover over nodes, highlight adjecent edges too\n", "graph.inspection_policy = NodesAndLinkedEdges()\n", "\n", "plot.add_tools(HoverTool(tooltips=None))\n", "\n", "show(plot)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "# Exercise: try a different inspection (or selection) policy like NodesOnly or EdgesAndLinkedNodes\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Next Section" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Click on this link to go to the next notebook: [09 - Geographic Plots](09%20-%20Geographic%20Plots.ipynb).\n", "\n", "To go back to the overview, click [here](00%20-%20Introduction%20and%20Setup.ipynb)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.2" } }, "nbformat": 4, "nbformat_minor": 4 }