Bokeh Tutorial

06. Linking and Interactions

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

Now that we know from the previous chapter how multiple plots can be placed together in a layout, we can start to look at how different plots can be linked together, or how plots can be linked to widgets.

Linked Interactions

It is possible to link various interactions between different Bokeh plots. For instance, the ranges of two (or more) plots can be linked, so that when one of the plots is panned (or zoomed, or otherwise has its range changed) the other plots will update in unison. It is also possible to link selections between two plots, so that when items are selected on one plot, the corresponding items on the second plot also become selected.

Linked panning

Linked panning (when multiple plots have ranges that stay in sync) is simple to spell with Bokeh. You simply share the appropriate range objects between two (or more) plots. The example below shows how to accomplish this by linking the ranges of three plots in various ways:

In [ ]:
from bokeh.layouts import gridplot

x = list(range(11))
y0, y1, y2 = x, [10-i for i in x], [abs(i-5) for i in x]

plot_options = dict(width=250, height=250, tools='pan,wheel_zoom')

# create a new plot
s1 = figure(**plot_options)
s1.circle(x, y0, size=10, color="navy")

# create a new plot and share both ranges
s2 = figure(x_range=s1.x_range, y_range=s1.y_range, **plot_options)
s2.triangle(x, y1, size=10, color="firebrick")

# create a new plot and share only one range
s3 = figure(x_range=s1.x_range, **plot_options)
s3.square(x, y2, size=10, color="olive")

p = gridplot([[s1, s2, s3]])

# show the results
show(p)
In [ ]:
# EXERCISE: create two plots in a gridplot, and link their ranges

Linked brushing

Linking selections is accomplished in a similar way, by sharing data sources between plots. Note that normally with bokeh.plotting and bokeh.charts creating a default data source for simple plots is handled automatically. However to share a data source, we must create them by hand and pass them explicitly. This is illustrated in the example below:

In [ ]:
from bokeh.models import ColumnDataSource

x = list(range(-20, 21))
y0, y1 = [abs(xx) for xx in x], [xx**2 for xx in x]

# create a column data source for the plots to share
source = ColumnDataSource(data=dict(x=x, y0=y0, y1=y1))

TOOLS = "box_select,lasso_select,help"

# create a new plot and add a renderer
left = figure(tools=TOOLS, width=300, height=300)
left.circle('x', 'y0', source=source)

# create another new plot and add a renderer
right = figure(tools=TOOLS, width=300, height=300)
right.circle('x', 'y1', source=source)

p = gridplot([[left, right]])

show(p)
In [ ]:
# EXERCISE: create two plots in a gridplot, and link their data sources

Hover Tools

Bokeh has a Hover Tool that allows additional information to be displayed in a popup whenever the user hovers over a specific glyph. Basic hover tool configuration amounts to providing a list of (name, format) tuples. The full details can be found in the User's Guide here.

The example below shows some basic usage of the Hover tool with a circle glyph, using hover information defined in utils.py:

In [ ]:
from bokeh.models import HoverTool

source = ColumnDataSource(
        data=dict(
            x=[1, 2, 3, 4, 5],
            y=[2, 5, 8, 2, 7],
            desc=['A', 'b', 'C', 'd', 'E'],
        )
    )

hover = HoverTool(
        tooltips=[
            ("index", "$index"),
            ("(x,y)", "($x, $y)"),
            ("desc", "@desc"),
        ]
    )

p = figure(width=300, height=300, tools=[hover], title="Mouse over the dots")

p.circle('x', 'y', size=20, source=source)

show(p)

Widgets

Bokeh supports direct integration with a small basic widget set. These can be used in conjunction with a Bokeh Server, or with CustomJS models to add more interactive capability to your documents. You can see a complete list, with example code in the Widgets and DOM elements section of the User's Guide.

NOTE: In this Tutorial chapter, we will focus on using widgets with JavaScript callbacks. The Tutorial chapter on Bokeh server applications covers using Bokeh widgets with real Python callbacks

To use the widgets, include them in a layout like you would a plot object:

In [ ]:
from bokeh.models import Slider


slider = Slider(start=0, end=10, value=1, step=.1, title="foo")

show(slider)
In [ ]:
# EXERCISE: create and show a Select widget 

CustomJS Callbacks

In order for a widget to be useful, it needs to be able to perform some action. Using the Bokeh server, it is possible to have widgets trigger real Python code. That possibility will be explored in the Bokeh server chapter of the tutorial. Here, we look at how widgets can be configured with CustomJS callbacks that execute snippets of JavaScript code.

In [ ]:
from bokeh.models import TapTool, CustomJS, ColumnDataSource

callback = CustomJS(code="alert('you tapped a circle!')")
tap = TapTool(callback=callback)

p = figure(width=600, height=300, tools=[tap])

p.circle(x=[1, 2, 3, 4, 5], y=[2, 5, 8, 2, 7], size=20)

show(p)

CustomJS for Property changes

Bokeh objects that have values associated can have small JavaScript actions attached to them using the js_on_change method. These actions (also referred to as "callbacks") are executed whenever the widget's value is changed. In order to make it easier to refer to specific Bokeh models (e.g., a data source, or a glyph) from JavaScript, the CustomJS object also accepts a dictionary of "args" that map names to Python Bokeh models. The corresponding JavaScript models are made available automatically to the CustomJS code:

CustomJS(args=dict(source=source, slider=slider), code="""
    // easily refer to BokehJS source and slider objects in this JS code
    var data = source.data;
    var f = slider.value;
""")

Slider widget example

The example below shows an action attached to a slider that updates a data source whenever the slider is moved.

In [ ]:
from bokeh.layouts import column
from bokeh.models import CustomJS, ColumnDataSource, Slider

x = [x*0.005 for x in range(0, 201)]

source = ColumnDataSource(data=dict(x=x, y=x))

plot = figure(width=400, height=400)
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)

slider = Slider(start=0.1, end=6, value=1, step=.1, title="power")

update_curve = CustomJS(args=dict(source=source, slider=slider), code="""
    const f = cb_obj.value
    const x = source.data.x
    const y = Array.from(x, (x) => Math.pow(x, f))
    source.data = { x, y }
""")
slider.js_on_change('value', update_curve)


show(column(slider, plot))
In [ ]:
# Exercise: Create a plot that updates based on a Select widget

Data selection example

It's also possible to make JavaScript actions that execute whenever a user selection (e.g., box, point, lasso) changes. This is done by attaching the same kind of CustomJS object to whatever data source the selection is made on.

The example below is a bit more sophisticated, and demonstrates updating one glyph's data source in response to another glyph's selection:

In [ ]:
from random import random

from bokeh.models import ColumnDataSource, CustomJS
from bokeh.plotting import figure, show

x = [random() for x in range(500)]
y = [random() for y in range(500)]
color = ["navy"] * len(x)

s = ColumnDataSource(data=dict(x=x, y=y, color=color))
p = figure(width=400, height=400, tools="lasso_select", title="Select Here")
p.circle('x', 'y', color='color', size=8, source=s, alpha=0.4,
         selection_color="firebrick")

s2 = ColumnDataSource(data=dict(x=[0, 1], ym=[0.5, 0.5]))
p.line(x='x', y='ym', color="orange", line_width=5, alpha=0.6, source=s2)

s.selected.js_on_change('indices', CustomJS(args=dict(s=s, s2=s2), code="""
    const inds = s.selected.indices
    if (inds.length > 0) {
        const ym = inds.reduce((a, b) => a + s.data.y[b], 0) / inds.length
        s2.data = { x: s2.data.x, ym: [ym, ym] }
    }
"""))

show(p)
In [ ]:
# Exercise: Experiment with selection callbacks

CustomJS for UI Events

Bokeh also has a general events system

All of the available UI events, and their properties, are listed in the Reference Guide section for bokeh.events

In [ ]:
from bokeh.plotting import figure
from bokeh import events
from bokeh.models import CustomJS, Div, Button
from bokeh.layouts import column, row

import numpy as np
x = np.random.random(size=2000) * 100
y = np.random.random(size=2000) * 100

p = figure(tools="box_select")
p.scatter(x, y, radius=1, fill_alpha=0.6, line_color=None)

div = Div(width=400)
button = Button(label="Button", width=300)
layout = column(button, row(p, div))

# Events with no attributes
button.js_on_event(events.ButtonClick,  CustomJS(args=dict(div=div), code="""
div.text = "Button!";
""")) 

p.js_on_event(events.SelectionGeometry, CustomJS(args=dict(div=div), code="""
div.text = "Selection! <p> <p>" + JSON.stringify(cb_obj.geometry, undefined, 2);
"""))

show(layout)
In [ ]:
# Exercise: Create a plot that responds to different events from bokeh.events

Additional Information

There are many kinds of interactions and events that can be connected to CustomJS callbacks.

  • Widgets - Button, Toggle, Dropdown, TextInput, AutocompleteInput, Select, Multiselect, Slider, (DateRangeSlider), DatePicker,
  • Tools - TapTool, BoxSelectTool, HoverTool,
  • Selection - ColumnDataSource, AjaxDataSource, BlazeDataSource, ServerDataSource
  • Ranges - Range1d, DataRange1d, FactorRange

For more complete examples the User Guide section on JavaScript Interactions

Next Section

Click on this link to go to the next notebook: 07 - Bar and Categorical Data Plots.

To go back to the overview, click here.