Bokeh is actually composed of two library components.
The first component is a JavaScript library, BokehJS, that runs in the browser. This library is responsible for all of the rendering and user interaction. Its input is a collection of declarative JSON objects that comprise a “scenegraph”. The objects in this scenegraph describe everything that BokehJS should handle: what plots and widgets are present and in what arrangement, what tools and renderers and axes the plots will have, etc. These JSON objects are converted into Backbone objects in the browser.
The second component is a library in Python (or other languages) that can generate the JSON described above. In the Python Bokeh library, this is accomplished at the lowest level by exposing a set of “model” classes that exactly mirror the set of Backbone Models that are created in the browser. Most of the models are very simple, usually consisting of a few property attributes and no methods. Model attributes can either be configured when the model is created, or later by setting attribute values on the model object:
glyph = Rect(x="x", y="y2", w=10, h=20, line_color=None)
glyph.fill_alpha = 0.5
glyph.fill_color = "navy"
These methods of configuration work in general for all Bokeh models. Because of that, and because all Bokeh interfaces ultimately produce collections of Bokeh models, styling and configuring plots and widgets is accomplished in basically the same way, regardless of which interface is used.
Using the bokeh.models interface provides complete control over how Bokeh plots and Bokeh widgets are put together and configured. However, it provides no help with assembling the models in meaningful or correct ways. It is entirely up to developers to build the scenegraph “by hand”.
For more information about the details of all Bokeh models, consult the Reference Guide.
Let's try to reproduce this NYTimes interactive chart Usain Bolt vs. 116 years of Olympic sprinters using the bokeh.models
interface.
The first thing we need is to get the data. The data for this chart is located in the bokeh.sampledata
module as a Pandas DataFrame. You can see the first ten rows below:
from bokeh.sampledata.sprint import sprint
sprint[:10]
Name | Country | Medal | Time | Year | |
---|---|---|---|---|---|
0 | Usain Bolt | JAM | GOLD | 9.63 | 2012 |
1 | Yohan Blake | JAM | SILVER | 9.75 | 2012 |
2 | Justin Gatlin | USA | BRONZE | 9.79 | 2012 |
3 | Usain Bolt | JAM | GOLD | 9.69 | 2008 |
4 | Richard Thompson | TRI | SILVER | 9.89 | 2008 |
5 | Walter Dix | USA | BRONZE | 9.91 | 2008 |
6 | Justin Gatlin | USA | GOLD | 9.85 | 2004 |
7 | Francis Obikwelu | POR | SILVER | 9.86 | 2004 |
8 | Maurice Greene | USA | BRONZE | 9.87 | 2004 |
9 | Maurice Greene | USA | GOLD | 9.87 | 2000 |
Next we import some of the Bokeh models that need to be assembled to make a plot. At a minimum, we need to start with Plot
, the glyphs (Circle
and Text
) we want to display, as well as ColumnDataSource
to hold the data and range obejcts to set the plot bounds.
from bokeh.io import output_notebook, show
from bokeh.models.glyphs import Circle, Text
from bokeh.models import ColumnDataSource, Range1d, DataRange1d, Plot
Next we need set up all the columns we want in our column data source. Here we add a few extra columns like MetersBack
and SelectedName
that we will use for a HoverTool
later.
abbrev_to_country = {
"USA": "United States",
"GBR": "Britain",
"JAM": "Jamaica",
"CAN": "Canada",
"TRI": "Trinidad and Tobago",
"AUS": "Australia",
"GER": "Germany",
"CUB": "Cuba",
"NAM": "Namibia",
"URS": "Soviet Union",
"BAR": "Barbados",
"BUL": "Bulgaria",
"HUN": "Hungary",
"NED": "Netherlands",
"NZL": "New Zealand",
"PAN": "Panama",
"POR": "Portugal",
"RSA": "South Africa",
"EUA": "United Team of Germany",
}
gold_fill = "#efcf6d"
gold_line = "#c8a850"
silver_fill = "#cccccc"
silver_line = "#b0b0b1"
bronze_fill = "#c59e8a"
bronze_line = "#98715d"
fill_color = { "gold": gold_fill, "silver": silver_fill, "bronze": bronze_fill }
line_color = { "gold": gold_line, "silver": silver_line, "bronze": bronze_line }
def selected_name(name, medal, year):
return name if medal == "gold" and year in [1988, 1968, 1936, 1896] else None
t0 = sprint.Time[0]
sprint["Abbrev"] = sprint.Country
sprint["Country"] = sprint.Abbrev.map(lambda abbr: abbrev_to_country[abbr])
sprint["Medal"] = sprint.Medal.map(lambda medal: medal.lower())
sprint["Speed"] = 100.0/sprint.Time
sprint["MetersBack"] = 100.0*(1.0 - t0/sprint.Time)
sprint["MedalFill"] = sprint.Medal.map(lambda medal: fill_color[medal])
sprint["MedalLine"] = sprint.Medal.map(lambda medal: line_color[medal])
sprint["SelectedName"] = sprint[["Name", "Medal", "Year"]].apply(tuple, axis=1).map(lambda args: selected_name(*args))
source = ColumnDataSource(sprint)
Let's build up our plot in stages, stopping to check the output along the way to see how things look.
As we go through, note the three methods that Plot
, Chart
, and Figure
all have:
p.add_glyph
p.add_tools
p.add_layout
These are actually small convenience methods that help us add models to Plot
objects in the correct way.
First we create just the Plot
with a title and some basic styling applied, as well add a few Circle
glyphs for the actual race data. To manually configure glyphs, we first create a glyph object (e.g., Text
or Circle
) that is configured with the visual properties we want as well as the data columns to use for coordinates, etc. Then we call plot.add_glyph
with the glyph, and the data source that the glyph should use.
plot_options = dict(plot_width=800, plot_height=480, toolbar_location=None, outline_line_color=None)
radius = dict(value=5, units="screen")
medal_glyph = Circle(x="MetersBack", y="Year", radius=radius, fill_color="MedalFill",
line_color="MedalLine", fill_alpha=0.5)
athlete_glyph = Text(x="MetersBack", y="Year", x_offset=10, text="SelectedName",
text_align="left", text_baseline="middle", text_font_size="9pt")
no_olympics_glyph = Text(x=7.5, y=1942, text=["No Olympics in 1940 or 1944"],
text_align="center", text_baseline="middle",
text_font_size="9pt", text_font_style="italic", text_color="silver")
xdr = Range1d(start=sprint.MetersBack.max()+2, end=0) # +2 is for padding
ydr = DataRange1d(range_padding=0.05)
plot = Plot(x_range=xdr, y_range=ydr, **plot_options)
plot.title.text = "Usain Bolt vs. 116 years of Olympic sprinters"
plot.add_glyph(source, medal_glyph)
plot.add_glyph(source, athlete_glyph)
plot.add_glyph(no_olympics_glyph)
<bokeh.models.renderers.GlyphRenderer at 0x10da19780>
show(plot)
Next we add in models for the Axis
and Grids
that we would like to see. Since we want to exert more control over the appearance, we can choose specific tickers for the axes models to use (SingleIntervalTicker
in this case). We add these guides to the plot using the plot.add_layout
method.
from bokeh.models import Grid, LinearAxis, SingleIntervalTicker
xdr = Range1d(start=sprint.MetersBack.max()+2, end=0) # +2 is for padding
ydr = DataRange1d(range_padding=0.05)
plot = Plot(x_range=xdr, y_range=ydr, **plot_options)
plot.title.text = "Usain Bolt vs. 116 years of Olympic sprinters"
plot.add_glyph(source, medal_glyph)
plot.add_glyph(source, athlete_glyph)
plot.add_glyph(no_olympics_glyph)
<bokeh.models.renderers.GlyphRenderer at 0x10da2a358>
xticker = SingleIntervalTicker(interval=5, num_minor_ticks=0)
xaxis = LinearAxis(ticker=xticker, axis_line_color=None, major_tick_line_color=None,
axis_label="Meters behind 2012 Bolt", axis_label_text_font_size="10pt",
axis_label_text_font_style="bold")
plot.add_layout(xaxis, "below")
xgrid = Grid(dimension=0, ticker=xaxis.ticker, grid_line_dash="dashed")
plot.add_layout(xgrid)
yticker = SingleIntervalTicker(interval=12, num_minor_ticks=0)
yaxis = LinearAxis(ticker=yticker, major_tick_in=-5, major_tick_out=10)
plot.add_layout(yaxis, "right")
show(plot)
Finally we add a hover tool to display those extra columns that we put into our column data source. We use the template syntax for the tooltips, to have more control over the appearance. Tools can be added using the plot.add_tools
method.
from bokeh.models import HoverTool
tooltips = """
<div>
<span style="font-size: 15px;">@Name</span>
<span style="font-size: 10px; color: #666;">(@Abbrev)</span>
</div>
<div>
<span style="font-size: 17px; font-weight: bold;">@Time{0.00}</span>
<span style="font-size: 10px; color: #666;">@Year</span>
</div>
<div style="font-size: 11px; color: #666;">@{MetersBack}{0.00} meters behind</div>
"""
xdr = Range1d(start=sprint.MetersBack.max()+2, end=0) # +2 is for padding
ydr = DataRange1d(range_padding=0.05)
plot = Plot(x_range=xdr, y_range=ydr, **plot_options)
plot.title.text = "Usain Bolt vs. 116 years of Olympic sprinters"
medal = plot.add_glyph(source, medal_glyph) # we need this renderer to configure the hover tool
plot.add_glyph(source, athlete_glyph)
plot.add_glyph(no_olympics_glyph)
xticker = SingleIntervalTicker(interval=5, num_minor_ticks=0)
xaxis = LinearAxis(ticker=xticker, axis_line_color=None, major_tick_line_color=None,
axis_label="Meters behind 2012 Bolt", axis_label_text_font_size="10pt",
axis_label_text_font_style="bold")
plot.add_layout(xaxis, "below")
xgrid = Grid(dimension=0, ticker=xaxis.ticker, grid_line_dash="dashed")
plot.add_layout(xgrid)
yticker = SingleIntervalTicker(interval=12, num_minor_ticks=0)
yaxis = LinearAxis(ticker=yticker, major_tick_in=-5, major_tick_out=10)
plot.add_layout(yaxis, "right")
hover = HoverTool(tooltips=tooltips, renderers=[medal])
plot.add_tools(hover)
show(plot)
from utils import get_gapminder_1964_data
def get_plot():
return Plot(
x_range=Range1d(1, 9), y_range=Range1d(20, 100),
plot_width=800, plot_height=400,
outline_line_color=None, toolbar_location=None,
)
df = get_gapminder_1964_data()
df.head()
fertility | life | population | region_color | |
---|---|---|---|---|
Afghanistan | 7.671 | 33.639 | 9.129985 | #fc8d59 |
Albania | 5.711 | 65.475 | 3.802632 | #e6f598 |
Algeria | 7.653 | 47.953 | 9.630513 | #fee08b |
American Samoa | NaN | NaN | 3.000000 | #99d594 |
Andorra | NaN | NaN | 3.000000 | #e6f598 |
# EXERCISE: Add Circles to the plot from the data in `df`.
# With `fertility` for the x coordinates, `life` for the y coordinates.
plot = get_plot()
# EXERCISE: Color the circles by region_color & change the size of the color by population
# EXERCISE: Add axes and grid lines
# EXERCISE: Manually add a legend using Circle & Text. The color key is as follows
region_name_and_color = [
('America', '#3288bd'),
('East Asia & Pacific', '#99d594'),
('Europe & Central Asia', '#e6f598'),
('Middle East & North Africa', '#fee08b'),
('South Asia', '#fc8d59'),
('Sub-Saharan Africa', '#d53e4f')
]
It is possible to extend the set of built-in Bokeh models with your own custom user models. The capability opens some valuable use-cases:
With this capability, advanced users can try out new features or techniques easily, without having to set up a full Bokeh development environment.
The basic outline of a custom model starts with a JavaScript implementation, which subclasses an existing BokehJS model:
JS_CODE = """
# These are similar to python imports. BokehJS vendors its own versions
# of Underscore and JQuery. They are available as show here.
_ = require "underscore"
$ = require "jquery"
# The "core/properties" module has all the property types
p = require "core/properties"
# We will subclass in JavaScript from the same class that was subclassed
# from in Python
LayoutDOM = require "models/layouts/layout_dom"
# This model will actually need to render things, so we must provide
# view. The LayoutDOM model has a view already, so we will start with that
class CustomView extends LayoutDOM.View
initialize: (options) ->
super(options)
@render()
# Set Backbone listener so that when the Bokeh slider has a change
# event, we can process the new data
@listenTo(@model.slider, 'change', () => @render())
render: () ->
# Backbone Views create <div> elements by default, accessible as @$el.
# Many Bokeh views ignore this default <div>, and instead do things
# like draw to the HTML canvas. In this case though, we change the
# contents of the <div>, based on the current slider value.
@$el.html("<h1>#{ @model.text }: #{ @model.slider.value }</h1>")
@$('h1').css({ 'color': '#686d8e', 'background-color': '#2a3153' })
class Custom extends LayoutDOM.Model
# If there is an associated view, this is boilerplate.
default_view: CustomView
# The ``type`` class attribute should generally match exactly the name
# of the corresponding Python class.
type: "Custom"
# The @define block adds corresponding "properties" to the JS model. These
# should basically line up 1-1 with the Python model class. Most property
# types have counterparts, e.g. bokeh.core.properties.String will be
# p.String in the JS implementation. Where the JS type system is not yet
# as rich, you can use p.Any as a "wildcard" property type.
@define {
text: [ p.String ]
slider: [ p.Any ]
}
# This is boilerplate. Every implementation should export a Model
# and (when applicable) also a View.
module.exports =
Model: Custom
View: CustomView
"""
This JavaScript implememtation is then attached to a corresponding Python Bokeh model:
from bokeh.core.properties import String, Instance
from bokeh.models import LayoutDOM, Slider
class Custom(LayoutDOM):
__implementation__ = JS_CODE
text = String(default="Custom text")
slider = Instance(Slider)
Then the new model can be used seamlessly in the same way as any built-in Bokeh model:
from bokeh.io import show
from bokeh.layouts import column
from bokeh.models import Slider
slider = Slider(start=0, end=10, step=0.1, value=0, title="value")
custom = Custom(text="Special Slider Display", slider=slider)
layout = column(slider, custom)
show(layout)