{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## 8. Graph and Network Plots\n", "\n", "This chapter will cover how to plot network node/link graphs in Bokeh using NetworkX. 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": [], "source": [ "from bokeh.io import show, output_notebook\n", "from bokeh.plotting import figure" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\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(\"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", " 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-2.4.3.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-gl-2.4.3.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.4.3.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.4.3.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-mathjax-2.4.3.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(\"1002\")).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(\"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 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-2.4.3.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-gl-2.4.3.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.4.3.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.4.3.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-mathjax-2.4.3.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(\"1002\")).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": [ "#nbi:hide_out\n", "# Make all outputs INLINE for default (why a hell this is needed !!!)\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": 3, "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 = {\"dda4bd43-30d7-4285-952e-1e1ace0209b9\":{\"defs\":[],\"roots\":{\"references\":[{\"attributes\":{\"renderers\":[{\"id\":\"1008\"}],\"title\":{\"id\":\"1028\"},\"toolbar\":{\"id\":\"1029\"},\"x_range\":{\"id\":\"1003\"},\"x_scale\":{\"id\":\"1026\"},\"y_range\":{\"id\":\"1004\"},\"y_scale\":{\"id\":\"1027\"}},\"id\":\"1005\",\"type\":\"Plot\"},{\"attributes\":{\"end\":2,\"start\":-2},\"id\":\"1004\",\"type\":\"Range1d\"},{\"attributes\":{\"coordinates\":null,\"group\":null},\"id\":\"1028\",\"type\":\"Title\"},{\"attributes\":{},\"id\":\"1043\",\"type\":\"Selection\"},{\"attributes\":{\"fill_color\":{\"value\":\"orange\"},\"size\":{\"value\":20}},\"id\":\"1009\",\"type\":\"Circle\"},{\"attributes\":{},\"id\":\"1026\",\"type\":\"LinearScale\"},{\"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\":\"1041\"},\"selection_policy\":{\"id\":\"1040\"}},\"id\":\"1010\",\"type\":\"ColumnDataSource\"},{\"attributes\":{\"coordinates\":null,\"data_source\":{\"id\":\"1010\"},\"glyph\":{\"id\":\"1009\"},\"group\":null,\"hover_glyph\":null,\"view\":{\"id\":\"1012\"}},\"id\":\"1011\",\"type\":\"GlyphRenderer\"},{\"attributes\":{\"end\":2,\"start\":-2},\"id\":\"1003\",\"type\":\"Range1d\"},{\"attributes\":{},\"id\":\"1042\",\"type\":\"UnionRenderers\"},{\"attributes\":{},\"id\":\"1029\",\"type\":\"Toolbar\"},{\"attributes\":{},\"id\":\"1039\",\"type\":\"NodesOnly\"},{\"attributes\":{\"line_dash\":{\"value\":[2,2]}},\"id\":\"1013\",\"type\":\"MultiLine\"},{\"attributes\":{\"source\":{\"id\":\"1010\"}},\"id\":\"1012\",\"type\":\"CDSView\"},{\"attributes\":{\"coordinates\":null,\"data_source\":{\"id\":\"1014\"},\"glyph\":{\"id\":\"1013\"},\"group\":null,\"hover_glyph\":null,\"view\":{\"id\":\"1016\"}},\"id\":\"1015\",\"type\":\"GlyphRenderer\"},{\"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\":\"1043\"},\"selection_policy\":{\"id\":\"1042\"}},\"id\":\"1014\",\"type\":\"ColumnDataSource\"},{\"attributes\":{\"source\":{\"id\":\"1014\"}},\"id\":\"1016\",\"type\":\"CDSView\"},{\"attributes\":{},\"id\":\"1040\",\"type\":\"UnionRenderers\"},{\"attributes\":{},\"id\":\"1041\",\"type\":\"Selection\"},{\"attributes\":{\"coordinates\":null,\"edge_renderer\":{\"id\":\"1015\"},\"group\":null,\"inspection_policy\":{\"id\":\"1039\"},\"layout_provider\":{\"id\":\"1017\"},\"node_renderer\":{\"id\":\"1011\"},\"selection_policy\":{\"id\":\"1038\"}},\"id\":\"1008\",\"type\":\"GraphRenderer\"},{\"attributes\":{},\"id\":\"1038\",\"type\":\"NodesOnly\"},{\"attributes\":{\"graph_layout\":{\"0\":[-1.1697191846420025,0.1173515414514772],\"1\":[-0.5057291920168522,-0.3301324932847872],\"10\":[0.5719975650503157,1.2631756750706118],\"11\":[1.313965098165436,0.7475138055892768],\"12\":[1.8,-0.26851044191988316],\"13\":[1.1664816220087437,-0.0959596247815966],\"14\":[0.13372947509740538,-0.3165161780939663],\"15\":[-0.5166063416282884,-1.3155585748399368],\"16\":[0.13524130085257552,-1.3686876436910196],\"17\":[1.2070076032178527,-1.1800792705596796],\"18\":[0.531189057176616,-0.7356351111910615],\"19\":[-0.10731944301045775,0.2842846361400993],\"2\":[0.19771666011850458,0.655978787503953],\"3\":[-0.5378765089311547,0.7138724373001639],\"4\":[-1.2210293189531412,1.1698194541672995],\"5\":[-1.7999176418742517,0.22483292849859016],\"6\":[-1.2970256277412264,-0.7904361743869417],\"7\":[-0.22598047907768307,-0.6182646310380427],\"8\":[0.48865747492340633,0.4088624653288193],\"9\":[-0.1647821187357951,1.4340884127366273]}},\"id\":\"1017\",\"type\":\"StaticLayoutProvider\"},{\"attributes\":{},\"id\":\"1027\",\"type\":\"LinearScale\"}],\"root_ids\":[\"1005\"]},\"title\":\"Bokeh Application\",\"version\":\"2.4.3\"}};\n", " const render_items = [{\"docid\":\"dda4bd43-30d7-4285-952e-1e1ace0209b9\",\"root_ids\":[\"1005\"],\"roots\":{\"1005\":\"3dc41e74-32d1-470e-a4ba-62c8a826ef98\"}}];\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": "1005" } }, "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": "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" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/javascript": [ "(function(root) {\n", " function embed_document(root) {\n", " const docs_json = {\"70f4192d-91f5-4be2-805d-96bc7590ba43\":{\"defs\":[],\"roots\":{\"references\":[{\"attributes\":{\"renderers\":[{\"id\":\"1159\"}],\"title\":{\"id\":\"1203\"},\"toolbar\":{\"id\":\"1182\"},\"x_range\":{\"id\":\"1154\"},\"x_scale\":{\"id\":\"1201\"},\"y_range\":{\"id\":\"1155\"},\"y_scale\":{\"id\":\"1202\"}},\"id\":\"1156\",\"type\":\"Plot\"},{\"attributes\":{\"coordinates\":null,\"group\":null},\"id\":\"1203\",\"type\":\"Title\"},{\"attributes\":{\"tools\":[{\"id\":\"1181\"}]},\"id\":\"1182\",\"type\":\"Toolbar\"},{\"attributes\":{\"fill_color\":{\"field\":\"colors\"},\"size\":{\"value\":20}},\"id\":\"1160\",\"type\":\"Circle\"},{\"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\":\"1216\"},\"selection_policy\":{\"id\":\"1215\"}},\"id\":\"1161\",\"type\":\"ColumnDataSource\"},{\"attributes\":{\"coordinates\":null,\"data_source\":{\"id\":\"1161\"},\"glyph\":{\"id\":\"1160\"},\"group\":null,\"hover_glyph\":null,\"view\":{\"id\":\"1163\"}},\"id\":\"1162\",\"type\":\"GlyphRenderer\"},{\"attributes\":{},\"id\":\"1216\",\"type\":\"Selection\"},{\"attributes\":{},\"id\":\"1202\",\"type\":\"LinearScale\"},{\"attributes\":{},\"id\":\"1217\",\"type\":\"UnionRenderers\"},{\"attributes\":{},\"id\":\"1164\",\"type\":\"MultiLine\"},{\"attributes\":{},\"id\":\"1218\",\"type\":\"Selection\"},{\"attributes\":{\"end\":2,\"start\":-2},\"id\":\"1154\",\"type\":\"Range1d\"},{\"attributes\":{\"source\":{\"id\":\"1161\"}},\"id\":\"1163\",\"type\":\"CDSView\"},{\"attributes\":{\"coordinates\":null,\"data_source\":{\"id\":\"1165\"},\"glyph\":{\"id\":\"1164\"},\"group\":null,\"hover_glyph\":null,\"view\":{\"id\":\"1167\"}},\"id\":\"1166\",\"type\":\"GlyphRenderer\"},{\"attributes\":{\"end\":2,\"start\":-2},\"id\":\"1155\",\"type\":\"Range1d\"},{\"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\":\"1218\"},\"selection_policy\":{\"id\":\"1217\"}},\"id\":\"1165\",\"type\":\"ColumnDataSource\"},{\"attributes\":{},\"id\":\"1201\",\"type\":\"LinearScale\"},{\"attributes\":{},\"id\":\"1213\",\"type\":\"NodesOnly\"},{\"attributes\":{},\"id\":\"1214\",\"type\":\"NodesOnly\"},{\"attributes\":{\"callback\":null,\"tooltips\":\"index: @index\"},\"id\":\"1181\",\"type\":\"HoverTool\"},{\"attributes\":{},\"id\":\"1215\",\"type\":\"UnionRenderers\"},{\"attributes\":{\"graph_layout\":{\"0\":[0.3887589353717005,-1.6463395451957297],\"1\":[1.3846658828275602,-0.9888706384388465],\"10\":[-0.3973296183215949,-1.1207122973322676],\"11\":[0.6918050631068496,-0.4881255395997623],\"12\":[0.06673400378400342,0.6367856992493871],\"13\":[-0.372190404725156,1.6549514681639979],\"14\":[0.7271639261632288,1.7891590455979385],\"15\":[0.3829194321748063,1.1235084976407805],\"16\":[0.8809036502719901,0.06648880890937106],\"17\":[-0.30216164550127095,-0.16880764210676003],\"18\":[-1.3471863197399672,-0.8450704388811822],\"19\":[-0.7146315969319081,-1.8],\"2\":[1.7420569157882306,-0.20269855379172452],\"3\":[1.348410997257696,0.8368982830124566],\"4\":[0.29447020642838123,0.1620331779290003],\"5\":[-0.06027364250284553,-0.6417199604835925],\"6\":[-0.6946893384592774,0.48328883898157654],\"7\":[-1.7429904289732252,0.20194290100155507],\"8\":[-1.3800370391698809,1.0068962141713491],\"9\":[-0.8963989788493182,-0.05960831882754418]}},\"id\":\"1168\",\"type\":\"StaticLayoutProvider\"},{\"attributes\":{\"source\":{\"id\":\"1165\"}},\"id\":\"1167\",\"type\":\"CDSView\"},{\"attributes\":{\"coordinates\":null,\"edge_renderer\":{\"id\":\"1166\"},\"group\":null,\"inspection_policy\":{\"id\":\"1214\"},\"layout_provider\":{\"id\":\"1168\"},\"node_renderer\":{\"id\":\"1162\"},\"selection_policy\":{\"id\":\"1213\"}},\"id\":\"1159\",\"type\":\"GraphRenderer\"}],\"root_ids\":[\"1156\"]},\"title\":\"Bokeh Application\",\"version\":\"2.4.3\"}};\n", " const render_items = [{\"docid\":\"70f4192d-91f5-4be2-805d-96bc7590ba43\",\"root_ids\":[\"1156\"],\"roots\":{\"1156\":\"9e407a9f-45bb-4eb3-909f-73567b47b0e0\"}}];\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": "1156" } }, "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": "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", "```python\n", " graph.inspection_policy = NodesAndLinkedEdges()\n", "```\n", "\n", "as the example below demonstrates." ] }, { "cell_type": "code", "execution_count": 5, "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 = {\"5837c009-ac4b-4df6-9471-bd6b0d156b93\":{\"defs\":[],\"roots\":{\"references\":[{\"attributes\":{\"renderers\":[{\"id\":\"1334\"}],\"title\":{\"id\":\"1406\"},\"toolbar\":{\"id\":\"1367\"},\"x_range\":{\"id\":\"1329\"},\"x_scale\":{\"id\":\"1404\"},\"y_range\":{\"id\":\"1330\"},\"y_scale\":{\"id\":\"1405\"}},\"id\":\"1331\",\"type\":\"Plot\"},{\"attributes\":{},\"id\":\"1405\",\"type\":\"LinearScale\"},{\"attributes\":{\"data\":{\"index\":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]},\"selected\":{\"id\":\"1418\"},\"selection_policy\":{\"id\":\"1417\"}},\"id\":\"1336\",\"type\":\"ColumnDataSource\"},{\"attributes\":{\"end\":2,\"start\":-2},\"id\":\"1329\",\"type\":\"Range1d\"},{\"attributes\":{\"fill_color\":{\"value\":\"#abdda4\"},\"size\":{\"value\":25}},\"id\":\"1354\",\"type\":\"Circle\"},{\"attributes\":{\"coordinates\":null,\"data_source\":{\"id\":\"1336\"},\"glyph\":{\"id\":\"1344\"},\"group\":null,\"hover_glyph\":{\"id\":\"1354\"},\"view\":{\"id\":\"1338\"}},\"id\":\"1337\",\"type\":\"GlyphRenderer\"},{\"attributes\":{\"tools\":[{\"id\":\"1366\"}]},\"id\":\"1367\",\"type\":\"Toolbar\"},{\"attributes\":{\"source\":{\"id\":\"1336\"}},\"id\":\"1338\",\"type\":\"CDSView\"},{\"attributes\":{\"coordinates\":null,\"group\":null},\"id\":\"1406\",\"type\":\"Title\"},{\"attributes\":{},\"id\":\"1364\",\"type\":\"NodesAndLinkedEdges\"},{\"attributes\":{\"line_color\":{\"value\":\"#abdda4\"},\"line_width\":{\"value\":4}},\"id\":\"1359\",\"type\":\"MultiLine\"},{\"attributes\":{\"coordinates\":null,\"data_source\":{\"id\":\"1340\"},\"glyph\":{\"id\":\"1349\"},\"group\":null,\"hover_glyph\":{\"id\":\"1359\"},\"view\":{\"id\":\"1342\"}},\"id\":\"1341\",\"type\":\"GlyphRenderer\"},{\"attributes\":{},\"id\":\"1417\",\"type\":\"UnionRenderers\"},{\"attributes\":{},\"id\":\"1404\",\"type\":\"LinearScale\"},{\"attributes\":{\"data\":{\"end\":[12,6,3,13,14,13,12,6,12,13,14,11,4,9,12,6,5,13,13,10,8,11,14,9,10,11,11,12,12,14],\"start\":[0,0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,4,4,5,5,6,7,7,7,9,9,10,10,11,11]},\"selected\":{\"id\":\"1420\"},\"selection_policy\":{\"id\":\"1419\"}},\"id\":\"1340\",\"type\":\"ColumnDataSource\"},{\"attributes\":{\"line_alpha\":{\"value\":0.8},\"line_color\":{\"value\":\"#cccccc\"},\"line_width\":{\"value\":2}},\"id\":\"1349\",\"type\":\"MultiLine\"},{\"attributes\":{},\"id\":\"1418\",\"type\":\"Selection\"},{\"attributes\":{\"end\":2,\"start\":-2},\"id\":\"1330\",\"type\":\"Range1d\"},{\"attributes\":{\"callback\":null,\"tooltips\":null},\"id\":\"1366\",\"type\":\"HoverTool\"},{\"attributes\":{\"source\":{\"id\":\"1340\"}},\"id\":\"1342\",\"type\":\"CDSView\"},{\"attributes\":{},\"id\":\"1420\",\"type\":\"Selection\"},{\"attributes\":{},\"id\":\"1419\",\"type\":\"UnionRenderers\"},{\"attributes\":{\"graph_layout\":{\"0\":[-0.4833281450441862,-0.23863243391835653],\"1\":[0.3568648536585474,0.4296361393270891],\"10\":[0.5777886700411361,0.3425039218236356],\"11\":[0.6058554964558718,-0.22501431324155174],\"12\":[-0.011015526964565358,0.17495954159548935],\"13\":[-0.35612534445256916,0.4355367121728019],\"14\":[0.8083581253680809,-0.3905562287059248],\"2\":[-0.8172910990866016,0.32376247349591875],\"3\":[0.1570810044630715,-0.5546962694608853],\"4\":[-0.1343029889959071,-0.022563134782480503],\"5\":[0.0271896160460196,0.7351840882226742],\"6\":[-1.046165508232688,-0.20491107595703953],\"7\":[1.2781533699086591,-0.3722266628588799],\"8\":[-1.8,-0.4515456212125839],\"9\":[0.8369374768351313,0.018562863500093597]}},\"id\":\"1343\",\"type\":\"StaticLayoutProvider\"},{\"attributes\":{},\"id\":\"1416\",\"type\":\"NodesOnly\"},{\"attributes\":{\"coordinates\":null,\"edge_renderer\":{\"id\":\"1341\"},\"group\":null,\"inspection_policy\":{\"id\":\"1364\"},\"layout_provider\":{\"id\":\"1343\"},\"node_renderer\":{\"id\":\"1337\"},\"selection_policy\":{\"id\":\"1416\"}},\"id\":\"1334\",\"type\":\"GraphRenderer\"},{\"attributes\":{\"fill_color\":{\"value\":\"#2b83ba\"},\"size\":{\"value\":25}},\"id\":\"1344\",\"type\":\"Circle\"}],\"root_ids\":[\"1331\"]},\"title\":\"Bokeh Application\",\"version\":\"2.4.3\"}};\n", " const render_items = [{\"docid\":\"5837c009-ac4b-4df6-9471-bd6b0d156b93\",\"root_ids\":[\"1331\"],\"roots\":{\"1331\":\"b16c5955-5218-48ed-a187-6639f276eb5a\"}}];\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": "1331" } }, "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)" ] } ], "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.7.9" } }, "nbformat": 4, "nbformat_minor": 4 }