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

Bokeh Tutorial

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

A1. Models and Primitives

" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Overview\n", "\n", "Although typically referred to by a single name, Bokeh comprises two separate libraries. \n", "\n", "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 JavaScript objects in the browser.\n", "\n", "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` subclasses that exactly mirror the set of BokehJS Models that are use 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:\n", "\n", "#### properties can be configured when a model object is initialized\n", "```python\n", "glyph = Rect(x=\"x\", y=\"y2\", w=10, h=20, line_color=None)\n", "```\n", "\n", "#### properties can be configured by assigning values to attributes on exitsting models\n", "```python\n", "glyph.fill_alpha = 0.5\n", "glyph.fill_color = \"navy\"\n", "```\n", "\n", "These methods of configuration work in general for all Bokeh models. \n", "\n", "Bokeh models are eventually collected into a Bokeh `Document` for serialization between BokehJS and the Bokeh Python bindings. As an example, the following image shows an example document for simple plot:\n", "\n", "![Document Structure](assets/document.svg)\n", "\n", "Such a document could be created at a high level using the `bokeh.plotting` API, which automatically assembles any models such as axes and grids and toolbars in a reasonable way. However it is also possible to assemble all the components \"by hand\" using the low-level `bokeh.models` API. 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”. \n", "\n", "For more information about the details of all Bokeh models, consult the [Reference Guide](https://bokeh.pydata.org/en/latest/docs/reference.html)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Example Walkthrough\n", "\n", "Let's try to reproduce this NYTimes interactive chart [Usain Bolt vs. 116 years of Olympic sprinters](http://www.nytimes.com/interactive/2012/08/05/sports/olympics/the-100-meter-dash-one-race-every-medalist-ever.html) using the `bokeh.models` interface." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from bokeh.sampledata.sprint import sprint\n", "sprint[:10]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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 objects to set the plot bounds. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from bokeh.io import output_notebook, show\n", "from bokeh.models import Circle, Text, ColumnDataSource, Range1d, DataRange1d, Plot" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "output_notebook()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Setting up Data\n", "\n", "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." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "abbrev_to_country = {\n", " \"USA\": \"United States\",\n", " \"GBR\": \"Britain\",\n", " \"JAM\": \"Jamaica\",\n", " \"CAN\": \"Canada\",\n", " \"TRI\": \"Trinidad and Tobago\",\n", " \"AUS\": \"Australia\",\n", " \"GER\": \"Germany\",\n", " \"CUB\": \"Cuba\",\n", " \"NAM\": \"Namibia\",\n", " \"URS\": \"Soviet Union\",\n", " \"BAR\": \"Barbados\",\n", " \"BUL\": \"Bulgaria\",\n", " \"HUN\": \"Hungary\",\n", " \"NED\": \"Netherlands\",\n", " \"NZL\": \"New Zealand\",\n", " \"PAN\": \"Panama\",\n", " \"POR\": \"Portugal\",\n", " \"RSA\": \"South Africa\",\n", " \"EUA\": \"United Team of Germany\",\n", "}\n", "\n", "fill_color = { \"gold\": \"#efcf6d\", \"silver\": \"#cccccc\", \"bronze\": \"#c59e8a\" }\n", "line_color = { \"gold\": \"#c8a850\", \"silver\": \"#b0b0b1\", \"bronze\": \"#98715d\" }\n", "\n", "def selected_name(name, medal, year):\n", " return name if medal == \"gold\" and year in [1988, 1968, 1936, 1896] else \"\"\n", "\n", "t0 = sprint.Time[0]\n", "\n", "sprint[\"Abbrev\"] = sprint.Country\n", "sprint[\"Country\"] = sprint.Abbrev.map(lambda abbr: abbrev_to_country[abbr])\n", "sprint[\"Medal\"] = sprint.Medal.map(lambda medal: medal.lower())\n", "sprint[\"Speed\"] = 100.0/sprint.Time\n", "sprint[\"MetersBack\"] = 100.0*(1.0 - t0/sprint.Time)\n", "sprint[\"MedalFill\"] = sprint.Medal.map(lambda medal: fill_color[medal])\n", "sprint[\"MedalLine\"] = sprint.Medal.map(lambda medal: line_color[medal])\n", "sprint[\"SelectedName\"] = sprint[[\"Name\", \"Medal\", \"Year\"]].apply(tuple, axis=1).map(lambda args: selected_name(*args))\n", "\n", "source = ColumnDataSource(sprint)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Building in stages\n", "\n", "Let's build up our plot in stages, stopping to check the output along the way to see how things look.\n", "\n", "As we go through, note the three methods that `Plot`, `Chart`, and `Figure` all have:\n", "\n", "* `p.add_glyph`\n", "* `p.add_tools`\n", "* `p.add_layout`\n", "\n", "These are actually small convenience methods that help us add models to `Plot` objects in the correct way." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Basic Plot with Just Glyphs\n", "\n", "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. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plot_options = dict(width=800, height=480, toolbar_location=None, outline_line_color=None)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "medal_glyph = Circle(x=\"MetersBack\", y=\"Year\", size=10, fill_color=\"MedalFill\", \n", " line_color=\"MedalLine\", fill_alpha=0.5)\n", "\n", "athlete_glyph = Text(x=\"MetersBack\", y=\"Year\", x_offset=10, text=\"SelectedName\",\n", " text_align=\"left\", text_baseline=\"middle\", text_font_size=\"9pt\")\n", "\n", "no_olympics_glyph = Text(x=7.5, y=1942, text=\"No Olympics in 1940 or 1944\",\n", " text_align=\"center\", text_baseline=\"middle\",\n", " text_font_size=\"9pt\", text_font_style=\"italic\", text_color=\"silver\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "xdr = Range1d(start=sprint.MetersBack.max()+2, end=0) # +2 is for padding\n", "ydr = DataRange1d(range_padding=0.05) \n", "\n", "plot = Plot(x_range=xdr, y_range=ydr, **plot_options)\n", "plot.title.text = \"Usain Bolt vs. 116 years of Olympic sprinters\"\n", "plot.add_glyph(source, medal_glyph)\n", "plot.add_glyph(source, athlete_glyph)\n", "plot.add_glyph(no_olympics_glyph)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "show(plot)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Adding Axes and Grids\n", "\n", "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. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from bokeh.models import Grid, LinearAxis, SingleIntervalTicker" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "xdr = Range1d(start=sprint.MetersBack.max()+2, end=0) # +2 is for padding\n", "ydr = DataRange1d(range_padding=0.05) \n", "\n", "plot = Plot(x_range=xdr, y_range=ydr, **plot_options)\n", "plot.title.text = \"Usain Bolt vs. 116 years of Olympic sprinters\"\n", "plot.add_glyph(source, medal_glyph)\n", "plot.add_glyph(source, athlete_glyph)\n", "plot.add_glyph(no_olympics_glyph)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "xticker = SingleIntervalTicker(interval=5, num_minor_ticks=0)\n", "xaxis = LinearAxis(ticker=xticker, axis_line_color=None, major_tick_line_color=None,\n", " axis_label=\"Meters behind 2012 Bolt\", axis_label_text_font_size=\"10pt\", \n", " axis_label_text_font_style=\"bold\")\n", "plot.add_layout(xaxis, \"below\")\n", "\n", "xgrid = Grid(dimension=0, ticker=xaxis.ticker, grid_line_dash=\"dashed\")\n", "plot.add_layout(xgrid)\n", "\n", "yticker = SingleIntervalTicker(interval=12, num_minor_ticks=0)\n", "yaxis = LinearAxis(ticker=yticker, major_tick_in=-5, major_tick_out=10)\n", "plot.add_layout(yaxis, \"right\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "show(plot)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Adding a Hover Tool\n", "\n", "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." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from bokeh.models import HoverTool" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tooltips = \"\"\"\n", "
\n", " @Name \n", " (@Abbrev)\n", "
\n", "
\n", " @Time{0.00} \n", " @Year\n", "
\n", "
@{MetersBack}{0.00} meters behind
\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "xdr = Range1d(start=sprint.MetersBack.max()+2, end=0) # +2 is for padding\n", "ydr = DataRange1d(range_padding=0.05) \n", "\n", "plot = Plot(x_range=xdr, y_range=ydr, **plot_options)\n", "plot.title.text = \"Usain Bolt vs. 116 years of Olympic sprinters\"\n", "medal = plot.add_glyph(source, medal_glyph) # we need this renderer to configure the hover tool\n", "plot.add_glyph(source, athlete_glyph)\n", "plot.add_glyph(no_olympics_glyph)\n", "\n", "xticker = SingleIntervalTicker(interval=5, num_minor_ticks=0)\n", "xaxis = LinearAxis(ticker=xticker, axis_line_color=None, major_tick_line_color=None,\n", " axis_label=\"Meters behind 2012 Bolt\", axis_label_text_font_size=\"10pt\", \n", " axis_label_text_font_style=\"bold\")\n", "plot.add_layout(xaxis, \"below\")\n", "\n", "xgrid = Grid(dimension=0, ticker=xaxis.ticker, grid_line_dash=\"dashed\")\n", "plot.add_layout(xgrid)\n", "\n", "yticker = SingleIntervalTicker(interval=12, num_minor_ticks=0)\n", "yaxis = LinearAxis(ticker=yticker, major_tick_in=-5, major_tick_out=10)\n", "plot.add_layout(yaxis, \"right\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "hover = HoverTool(tooltips=tooltips, renderers=[medal])\n", "plot.add_tools(hover)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "show(plot)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Exercises" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Custom User Models\n", "\n", "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:\n", "* customizing existing Bokeh model behaviour\n", "* wrapping and connecting other JS libraries to Bokeh\n", "\n", "With this capability, advanced users can try out new features or techniques easily, without having to set up a full Bokeh development environment. \n", "\n", "The section gives a basi outline of a custom model starts with a JavaScript implementation, which subclasses an existing BokehJS model. Full details can be found in the [Extending Bokeh](https://bokeh.pydata.org/en/latest/docs/user_guide/extensions.html) chapter of the User's Guide." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Implement the JavaScript Model" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "CODE = \"\"\"\n", "import {UIElement, UIElementView} from \"models/ui/ui_element\"\n", "import {Slider} from \"models/widgets/slider\"\n", "import {div} from \"core/dom\"\n", "import * as p from \"core/properties\"\n", "\n", "export class CustomView extends UIElementView {\n", " model: Custom\n", "\n", " private content_el: HTMLElement\n", "\n", " override connect_signals(): void {\n", " super.connect_signals()\n", " this.connect(this.model.slider.change, () => this._update_text())\n", " }\n", "\n", " override render(): void {\n", " // BokehJS views create
elements by default. These are accessible\n", " // as ``this.el``. Many Bokeh views ignore the default
and\n", " // instead do things like draw to the HTML canvas. In this case though,\n", " // the program changes the contents of the
based on the current\n", " // slider value.\n", " super.render()\n", "\n", " this.content_el = div({style: {\n", " textAlign: \"center\",\n", " fontSize: \"1.2em\",\n", " padding: \"2px\",\n", " color: \"#b88d8e\",\n", " backgroundColor: \"#2a3153\",\n", " }})\n", " this.shadow_el.appendChild(this.content_el)\n", "\n", " this._update_text()\n", " }\n", "\n", " private _update_text(): void {\n", " this.content_el.textContent = `${this.model.text}: ${this.model.slider.value}`\n", " }\n", "}\n", "\n", "export namespace Custom {\n", " export type Attrs = p.AttrsOf\n", "\n", " export type Props = UIElement.Props & {\n", " text: p.Property\n", " slider: p.Property\n", " }\n", "}\n", "\n", "export interface Custom extends Custom.Attrs {}\n", "\n", "export class Custom extends UIElement {\n", " properties: Custom.Props\n", " __view_type__: CustomView\n", "\n", " constructor(attrs?: Partial) {\n", " super(attrs)\n", " }\n", "\n", " static {\n", " // If there is an associated view, this is typically boilerplate.\n", " this.prototype.default_view = CustomView\n", "\n", " // The this.define() block adds corresponding \"properties\" to the JS\n", " // model. These should normally line up 1-1 with the Python model\n", " // class. Most property types have counterparts. For example,\n", " // bokeh.core.properties.String will correspond to ``String`` in the\n", " // JS implementation. Where JS lacks a given type, you can use\n", " // ``p.Any`` as a \"wildcard\" property type.\n", " this.define(({String, Ref}) => ({\n", " text: [ String, \"Custom text\" ],\n", " slider: [ Ref(Slider) ],\n", " }))\n", " }\n", "}\n", "\"\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Define the Python Model\n", "\n", "This JavaScript implementation is then attached to a corresponding Python Bokeh model:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from bokeh.core.properties import Instance, Required, String\n", "\n", "class Custom(UIElement):\n", "\n", " __implementation__ = TypeScript(CODE)\n", "\n", " text = String(default=\"Custom text\")\n", "\n", " slider = Required(Instance(Slider))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Use the Python Model\n", "\n", "Then the new model can be used seamlessly in the same way as any built-in Bokeh model:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from bokeh.io import show, output_file\n", "from bokeh.layouts import column\n", "from bokeh.models import Slider\n", "\n", "slider = Slider(start=0, end=10, step=0.1, value=0, title=\"value\")\n", "\n", "custom = Custom(text=\"Special Slider Display\", slider=slider)\n", "\n", "layout = column(slider, custom)\n", "\n", "show(layout)\n", "\n", "# Necessary to explicitly reload BokehJS to pick up new extension code\n", "output_notebook()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "show(layout)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Next Section" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To explore the next topic in the appendices, click on this link: [A2 - Visualizing Big Data with Datashader](A2%20-%20Visualizing%20Big%20Data%20with%20Datashader.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": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.9.13" } }, "nbformat": 4, "nbformat_minor": 4 }