Bokeh Tutorial

08. Graph and Network Plots

In [1]:
from bokeh.io import show, output_notebook
from bokeh.plotting import figure

output_notebook()
Loading BokehJS ...
In [2]:
import networkx as nx

G = nx.desargues_graph()
In [3]:
from bokeh.models.graphs import from_networkx
from bokeh.models import Range1d, Plot

# We could use figure here but don't want all the axes and titles
plot = Plot(x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1))

# Create a Bokeh graph from the NetworkX input using nx.spring_layout
graph = from_networkx(G, nx.spring_layout, scale=2, center=(0,0))
plot.renderers.append(graph)

# Set some of the default node glyph (Circle) properties
graph.node_renderer.glyph.update(size=20, fill_color="orange")

show(plot)
In [4]:
# Exercise: try a different NetworkX layout, and set some `graph.edge_renderer` properties
In [5]:
from bokeh.models.graphs import NodesAndLinkedEdges
from bokeh.models import Circle, HoverTool, MultiLine

G = nx.karate_club_graph()

# We could use figure here but don't want all the axes and titles
plot = Plot(x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1))

# Create a Bokeh graph from the NetworkX input using nx.spring_layout
graph = from_networkx(G, nx.spring_layout, scale=2, center=(0,0))
plot.renderers.append(graph)

# Blue circles for nodes, and light grey lines for edges
graph.node_renderer.glyph = Circle(size=25, fill_color='#2b83ba')
graph.edge_renderer.glyph = MultiLine(line_color="#cccccc", line_alpha=0.8, line_width=2)

# green hover for both nodes and edges
graph.node_renderer.hover_glyph = Circle(size=25, fill_color='#abdda4')
graph.edge_renderer.hover_glyph = MultiLine(line_color='#abdda4', line_width=4)

# When we hover over nodes, highlight adjecent edges too
graph.inspection_policy = NodesAndLinkedEdges()

plot.add_tools(HoverTool(tooltips=None))

show(plot)
In [6]:
# Exercise: try a different inspection (or selection) policy