Getting Started with Bokeh for Python
By: Emile Gill
Tags: Programming, Bokeh, Getting Started, Data Science, Data Visualization

Getting started with Bokeh

Effortlessly elegant interactive data visualisations in Python

Photo by Denise Johnson on Unsplash

In this article I aim to give you an introduction to Bokeh, detailing what it is, why you should be using it and how you can easily get started!

What is Bokeh?

Bokeh is a neat Python library that allows us to quickly and easily create high-performance, professional interactive data visualisations and web apps. You can check out some examples of the power and range of what Bokeh can do here.

An example of what can be done with Bokeh.

Bokeh’s most enticing quality is that it manages to balance both simplicity- with very few lines of code required to create complex interactive visualisations- and the flexibility for advanced customisation, should you require it. Whether you simply want to create prettier graphs in your Jupyter notebooks, or develop and deploy complete web applications, Bokeh is a great visualisation tool for any Python user to have.

Fundamentals of Bokeh

Plots

Bokeh’s Plot class, provides the canvas on which we can build our visualisations. To get started creating a visualisation in Bokeh we can simply instantiate a figure object:

If we were to run the above code we would produce a blank figure object, which would then be output as an HTML file, saved to the path specified, and then displayed in a new tab of a web browser. We could also have used the output_notebook() function, if we were working in a Jupyter notebook and wanted to display our visualisation directly in an output cell.

This isn’t very inspiring so far, as we’ve yet to add any data- but we’ll see in the next section how we can start building on top of our figure to quickly add detail to our plot.

Glyphs

Glyphs are the most fundamental plotting unit in Bokeh. They essentially consist of visual markers, with attributes that may be associated with our data. From simple line glyphs, to hexagonal grids of tiles (HexTile glyph), there are a multitude of different glyphs available to us, depending on our visualisation needs.

We can extend the above code, to add a glyph to our figure, as simply as:

The power of Bokeh is visible immediately. With a single additional line of code, we have added some data to our plot which we can fiddle with and explore instantly with Bokeh’s out of the box interactivity. The plot tools visible on the right of the figure enable us to drag, zoom and reset our plot. We can even save our view to an image file, using the SaveTool feature.

Exploring Bokeh’s inbuilt plot tools, with a simple line glyph.

You can explore the variety of glyphs we are able to choose from, and their associated attributes, here.

Adding multiple glyphs to a figure is no issue, we simply call all the glyph methods we require separately and Bokeh will layer them onto our figure in the order specified.

Multiple glyphs overlayed on a figure.

Data Sources

It couldn’t be easier to specify our data to Bokeh objects. Bokeh is compatible with the familiar data formats of lists, NumPy arrays and pandas DataFrames; all of which we can pass directly as arguments to glyph methods.

Line glyph from NumPy source data.

Bokeh also comes inbuilt with its own data format, the ColumnDataSource. This forms the fundamental underlying data structure used by Bokeh objects. In fact, when we supply lists, NumPy arrays, or pandas DataFrames to Bokeh, these are implicitly converted to ColumnDataSource objects behind the scenes. ColumnDataSources make it easy to share data between glyphs and link the selected data, as well as allowing us to supply additional data, which, as we will see later, can be used to add annotations to our visualisation.

We can define a ColumnDataSource in the following manner:

Once we have defined a ColumnDataSource, we can easily access data by simply specifying its column name, and passing our CDS as the source parameter of a plotting method. Below we create an example plot using one of Bokeh’s sample CSV datasets that we read into a pandas DataFrame and then convert to a ColumnDataSource.

Apple stock opening price over time (dataset from Bokeh’s sample data).

Customising Visualisations

Configuring Plot Tools

As we have seen from instantiating a figure object in Bokeh, plots come with various inbuilt interactive features. If we do not articulate these explicitly, Bokeh will provide the default suite of tools. However, should we wish, we may also define these when creating our figure object:

You can explore all the plot tool options that are available in the official documentation here.

HoverTools

One of the plot tools we have available in Bokeh, deserving of its own section, is the HoverTool class. This is a neat feature that allows us to uncover additional details from our data, simply by hovering above an object.

We can specify a HoverTool by providing a list of (label, value) tuples for the data we wish to be included.

Field names prepended with @ are associated with ColumnDataSource column headers and names beginning with $ are “special fields” corresponding to plot metadata such as $index (index of data point), $x (x-coordinate of cursor).

Adding a hover tool to our Apple stock plot.

Colour Mapping

Bokeh provides various inbuilt colour palettes for us to choose from, the full list of which can be found here. A useful feature for styling our visualised data with a specified palette is the “Color Mappers” available to us in Bokeh. These allow us to visually elucidate some property of the data, depending on its value.

For example, the linear_cmap function allows us to assign colours depending on a value’s position on a linear scale:

Example of a linear colour-mapping, applied to our previous sine plot.

Similarly a log_cmap function exists, working in exactly the same manner but with a logarithmic scale. We can even include a ColorBar alongside out plot to explicate the mapping of colours to values.

For categorical data, we can use the CategoricalColorMapper class to define a relationship between various categorical factors and a specified colour palette. Bokeh has a detailed guide for handling categorical data here, where you can read more about this should you wish.

Annotations

Annotations such as titles, legends, axis labels, data labels can also be added to plots. There are many different options to customise our plots here; I will not delve into too much detail on these as there is plenty of good documentation on what can be done here and here.

The below example shows some of the most common properties we might want to define when creating a figure:

Arranging Plots

If we have multiple plots that we want to combine in the same output, we can use the bokeh.layouts module to define how these are arranged.

Row and Columns

The row and column functions allow us to organise plots into rows, columns, or a nested layout formed of some combination of the two.

Grids

A uniform grid of plots is easy to create using the gridplot function.

Tabs

We can even display our visualisations in a tabbed layout, with the ability to toggle between different plots.

Linked Plots

To link the axes of plots, we can simply define their axis range attributes to be equal:

p3.x_range = p2.x_range = p1.x_range

p3.y_range = p2.y_range = p1.y_range

To link the selection of data in our visualisations, all that is required is for them to share the same data source:

Conclusion

Photo by Josh Boot on Unsplash

We are now well equipped with the fundamentals of Bokeh and should have everything we need to get started experimenting and creating our own custom visualisations. That said, this is only the tip of the iceberg when it comes to Bokeh’s full capabilities as a visualisation tool.

In my next post we will explore how to take what we have learned one stage further, and transition from creating beautiful visualisations to developing captivating web applications, with even more interactivity. I’ll see you back then, but for now:

Thanks for reading!