Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 31 ยท Bokeh

Bokeh Fundamentals

Learn Bokeh basics: create a figure, draw line, scatter and vbar glyphs, share data with ColumnDataSource, save to HTML, and see how the JSON document model works.

Bokeh is a Python library for interactive charts that run in the browser. It takes a different path than Plotly Express. Instead of one function per chart type, Bokeh gives you a blank figure and a set of glyphs: the basic shapes (lines, circles, bars, patches, wedges) that you place on it. A chart is whatever you build from those shapes. This takes a few more lines than a one-liner, and in return you get fine control and a very clean model for interaction, which the next lessons use.

This lesson covers the building blocks: figure, glyph methods, ColumnDataSource, saving and showing, and the document model that explains how a Python object becomes an interactive page. If you have not yet chosen a library, Interactive Data Visualization: The Big Picture compares the three.

Bokeh needs a Python install and its browser library (BokehJS), so it cannot run on this site. The Bokeh code below is read-only. The runnable examples are stand-ins written in plain Python: one models a ColumnDataSource as a table of equal-length columns, the other models a figure that records glyphs and prints a JSON-like document. They show the design, not Bokeh's actual classes.

Your first Bokeh chart

Install with pip install bokeh. Then:

Python
from bokeh.plotting import figure, show, output_file

months = ["Jan", "Feb", "Mar", "Apr", "May"]
sales = [120, 150, 90, 180, 160]

output_file("sales.html")  # where show() writes the page

p = figure(
    x_range=months,          # a list of strings makes a categorical axis
    height=350,
    title="Sales by month",
    toolbar_location="above",
)
p.vbar(x=months, top=sales, width=0.7, color="steelblue")
p.yaxis.axis_label = "USD (thousands)"
p.xgrid.grid_line_color = None

show(p)

figure(...) creates the plot: size, title, axis ranges, toolbar. p.vbar(...) adds a glyph renderer that draws one vertical bar per data point. show(p) writes an HTML file (here sales.html) and opens it in your browser. The file loads BokehJS from a CDN, so you need to be online to open it unless you configure local resources (see Exporting, Embedding and Sharing Charts).

In a Jupyter notebook, call output_notebook() once, and show(p) displays the chart inline.

Glyphs

Each glyph method adds one kind of mark:

Python
p.line(x, y, line_width=2)                # a connected line
p.scatter(x, y, size=9, marker="circle")  # points; marker can be "square", "triangle", ...
p.vbar(x=x, top=y, width=0.8)             # vertical bars; hbar for horizontal
p.varea(x=x, y1=low, y2=high, alpha=0.3)  # filled band between two curves
p.patch(xs, ys)                           # a polygon

You can place as many glyphs on a figure as you like, which is how you combine a line with markers or draw a confidence band under a curve. (In older tutorials you will see p.circle(...). In current Bokeh 3.x versions scatter with a marker is the recommended way, and the old circle shortcut with size is deprecated.)

Glyph options describe appearance: color, line_color, fill_color, line_width, alpha, legend_label="..." and so on. Axis and grid styling happens on the figure afterwards: p.xaxis.axis_label, p.yaxis.formatter, p.legend.location, p.toolbar.autohide = True.

ColumnDataSource: the data behind the marks

In the first example, the lists were passed directly to vbar. Bokeh quietly wraps them in a ColumnDataSource, a table of named columns. You get more control by creating one yourself and referring to its columns by name:

Python
from bokeh.models import ColumnDataSource

source = ColumnDataSource(data={
    "month": months,
    "sales": sales,
    "target": [130, 130, 130, 160, 160],
})

p = figure(x_range=months, height=350)
p.vbar(x="month", top="sales", width=0.7, source=source)
p.line(x="month", y="target", source=source, line_width=2, color="tomato")

When you pass source=..., strings in glyph arguments are read as column names. Several practical benefits follow:

  • One source, many glyphs. The bars and the line read the same columns; no data is duplicated.
  • Hover and selection use the columns. Tooltips can show @sales or @target, and selecting a bar means selecting row indexes of the source (Bokeh Tools, Hover and Widgets).
  • Linked views. Two figures that use the same source object select together.
  • Updates. You can change or append data in the source and the chart updates (Bokeh Server and Streaming Data).

A ColumnDataSource can be built from a dictionary, from a pandas DataFrame (ColumnDataSource(df), which also adds an index column), or from other column-like objects. Every column must be the same length. Bokeh will complain if they are not, because one row of the table has to exist for every mark.

The first stand-in builds that idea in plain Python: a table of columns with the length rule, row access and a selection list. Run it to see how a "selected" set of row indexes is all that selection really is.

Python A ColumnDataSource-like table (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The final lines are the key idea: selecting marks means choosing row indexes. Every glyph and tool that uses the same source sees the same selection.

Saving and showing

There are four common ways to get a figure out of Python:

Goal Code
Open in a browser tab output_file("chart.html") then show(p)
Write a file without opening save(p) (imported from bokeh.io)
Show in a notebook output_notebook() then show(p)
Embed in your own page from bokeh.embed import components, json_item, file_html

components(p) returns a script and a <div> to paste into a page, and json_item(p, "target-id") returns JSON that your JavaScript passes to Bokeh.embed.embed_item. This is the route when a Flask or Django app serves charts. Static PNG or SVG export is also available through the bokeh.io export functions and needs a headless browser installed.

Layouts combine figures: row(p1, p2), column(p1, p2) and gridplot([[p1, p2], [p3, p4]]) from bokeh.layouts.

The document model

Everything in Bokeh is a model: the figure, each axis, each glyph renderer, the data source, the toolbar. Python models and BokehJS models mirror each other. When you call show, Bokeh serializes the whole graph of models into a JSON document, and BokehJS rebuilds the same graph in the browser and draws it. A model in the JSON has a type, an id and a set of attributes; one model refers to another by its id. That is why two glyphs can point to the same data source: they hold the same id.

flowchart TD
    D["Document (JSON)"] --> F["Figure"]
    F --> A["Axes and grids"]
    F --> R1["GlyphRenderer: bars"]
    F --> R2["GlyphRenderer: line"]
    R1 --> S["ColumnDataSource"]
    R2 --> S
    R1 --> G1["Glyph: VBar"]
    R2 --> G2["Glyph: Line"]

Both renderers refer to one ColumnDataSource, so they share data and selection.

This model is what makes Bokeh's interactivity work in two worlds. In a static HTML file, the JSON travels inside the page and JavaScript callbacks react in the browser. With a Bokeh server (a later lesson), the same models stay in sync with a Python process over a connection.

The second stand-in shows the idea with a tiny figure class. It records glyph calls, resolves column names against a source, creates ids, and prints a JSON-like document where both renderers hold the id of the shared source. The real Bokeh JSON has more fields and a different layout; this is only the shape of the idea.

Python A figure that records glyphs and prints a document (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that both renderers carry the same data_source id and that a typo in a column name is caught when the glyph is created. Bokeh behaves similarly: a column name that does not exist in the source produces an error message in the browser console or a warning at build time, depending on the case.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is a glyph in Bokeh?

    Glyph methods like line, scatter and vbar add shapes to a figure. A chart is built from one or more glyphs.
  2. 2. When you pass source=source to a glyph method, what does a string such as 'sales' mean?

    With a source, strings are looked up as column names. That is how several glyphs read the same table.
  3. 3. Why do two figures that share one ColumnDataSource select together?

    Selection is a property of the data source (the chosen row indexes), so every glyph and figure using that source reflects it.
  4. 4. Which call writes the chart to an HTML file and opens it?

    output_file sets the destination and show writes the page and opens it. output_notebook targets a Jupyter notebook instead.
  5. 5. What is true about the columns of a ColumnDataSource?

    Each row of the table has one value per column, so all columns need the same number of entries. Values can be text, numbers, dates and more.

Summary

  • A Bokeh chart is a figure plus glyphs such as line, scatter, vbar and varea.
  • A ColumnDataSource holds named, equal-length columns; glyphs refer to columns by name and many glyphs can share one source.
  • output_file + show writes and opens an HTML page; output_notebook, save, components and json_item cover notebooks and embedding.
  • Under the hood every object is a model in a JSON document that BokehJS rebuilds in the browser; models refer to each other by id.
  • Selection is a set of row indexes on the source, which is why shared sources give linked views.
  • The Bokeh code here is read-only; the runnable examples are plain-Python stand-ins.

Next: Bokeh Tools, Hover and Widgets.