A Gentle Introduction to Bokeh: Interactive Python Plotting Library

Data visualization is an essential skill for any data scientist or analyst. While static plots can convey information, interactive plots engage users and allow them to explore data in ways impossible with images alone. Bokeh is an incredibly powerful Python library that makes it easy to create interactive, web-ready plots, dashboards, and data applications. Let‘s take a deep dive into what Bokeh has to offer.

What is Bokeh?

Bokeh is an interactive visualization library for Python that targets modern web browsers for presentation. It was created by Anaconda (formerly Continuum Analytics) in 2013 and has quickly become one of the most popular tools for data visualization in Python.

Some of the key features of Bokeh include:

  • Flexible, customizable, and easy-to-use API
  • Interactive pan, zoom, and selection tools
  • Support for large and streaming datasets
  • Standalone HTML output or embeddable in web apps
  • Ability to hook into Python callbacks for dynamic updates

Under the hood, Bokeh creates visualizations using HTML and JavaScript. However, you don‘t need to know anything about those technologies to use Bokeh. The library abstracts away the details and lets you work entirely in Python.

Installing and Configuring Bokeh

Installing Bokeh is a snap using pip, the standard Python package manager:

pip install bokeh

This command will install the latest version of Bokeh and all of its dependencies. As of April 2023, the current version is 3.1.0.

If you‘re using Bokeh in a Jupyter notebook, you‘ll also want to load the Bokeh extension for displaying plots inline:

from bokeh.io import output_notebook
output_notebook()

With those simple steps, you‘re ready to start creating interactive visualizations in Python!

Basic Plotting with Bokeh

Bokeh provides a concise yet flexible API for programmatically describing visual glyphs and defining how they map to data. Let‘s walk through some basic examples of common plot types.

Line and Scatter Plots

Line and scatter plots are a great way to visualize trends and relationships between variables. Here‘s an example of plotting a simple sine wave:

from bokeh.plotting import figure, show

x = [1, 2, 3, 4, 5]
y = [6, 7, 2, 4, 5]

p = figure(title="Simple Line Plot", x_axis_label=‘x‘, y_axis_label=‘y‘)

p.line(x, y, legend_label="Trend", line_width=2)
p.scatter(x, y, legend_label="Points", fill_color="white", size=8)

show(p)

This code produces an interactive plot with pan and zoom tools enabled by default. The legend allows you to hide or mute the line and scatter glyphs.

Bar Charts

Bar charts are useful for comparing discrete categories. Bokeh supports both categorical and numeric bar charts. Here‘s an example using categorical variables:

from bokeh.plotting import figure, show

fruits = [‘Apples‘, ‘Pears‘, ‘Oranges‘, ‘Bananas‘]
counts = [5, 3, 4, 2]

p = figure(x_range=fruits, height=350, title="Fruit Counts",
           toolbar_location=None, tools="")

p.vbar(x=fruits, top=counts, width=0.9)

p.xgrid.grid_line_color = None
p.y_range.start = 0

show(p)

For numeric bar charts, simply pass the x-coordinates directly:

from bokeh.plotting import figure, show

x = [1, 2, 3, 4, 5]
y = [6, 7, 2, 4, 5]

p = figure(title="Numeric Bar Chart")

p.vbar(x=x, top=y, width=0.5)

show(p)  

Patch Plots

Patch plots are a handy way to visualize geographic regions or arbitrary polygons. Bokeh can plot patches either from a list of points or from separate lists of x and y coordinates.

Here‘s an example that generates and plots a circle:

from bokeh.plotting import figure, show

N = 80
r = 2
theta = np.linspace(0, 2*np.pi, N)
x = r*np.cos(theta)
y = r*np.sin(theta)

p = figure(x_range=(-2.5, 2.5), y_range=(-2.5, 2.5))
p.patch(x, y, alpha=0.5, line_width=2)

show(p)

Customizing Appearance

Bokeh provides a ton of options for customizing the appearance of your plots, from colors and background shading to tick marks and labels. Most glyph methods accept standard styling options like fill_color, fill_alpha, line_color, and line_width.

You can also control the appearance of the overall plot, including things like outlines, backgrounds, and grid lines, using the outline_line_* and background_fill_* properties on the plot object itself.

Here‘s an example showcasing a few appearance customizations:

from bokeh.plotting import figure, show

p = figure(width=400, height=400)
p.outline_line_width = 7
p.outline_line_alpha = 0.3
p.outline_line_color = "navy"

p.circle([1,2,3,4,5], [2,5,8,2,7], size=10, color="firebrick", alpha=0.5)

p.background_fill_color = "lightgrey"
p.background_fill_alpha = 0.3

p.xaxis.minor_tick_line_color = "navy"
p.yaxis.major_label_orientation = "vertical"

show(p) 

Positioning and Layout

Bokeh includes several options for controlling the position and layout of plots, including:

  • row and column for arranging multiple plots vertically or horizontally
  • grid for 2D grid layouts
  • Tabs and Panels for organizing plots with tabs
  • Linked panning and brushing

Here‘s an example that lays out two plots in a grid and links their axes:

from bokeh.layouts import gridplot
from bokeh.plotting import figure, show

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

# create a new plot
s1 = figure(plot_width=250, plot_height=250)
s1.circle(x, y0, size=10, color="navy", alpha=0.5)

# create another one
s2 = figure(plot_width=250, plot_height=250)
s2.triangle(x, y1, size=10, color="firebrick", alpha=0.5)

# put the results in a grid
p = gridplot([[s1, s2]], toolbar_location=None)

# link axes
s2.x_range = s1.x_range
s2.y_range = s1.y_range

show(p)

Bokeh for Data Science

One of the most powerful features of Bokeh is its ability to handle large and streaming datasets. Bokeh‘s efficient WebGL rendering can smoothly handle plots with over 100,000 data points, making it a great choice for big data visualization.

Here are a few examples of how Bokeh has been used for data science and machine learning:

  • Visualizing geographic data on interactive maps
  • Plotting real-time sensor readings or financial data
  • Exploring machine learning models and decision boundaries
  • Building dashboards to monitor training progress and model performance

To further optimize performance, Bokeh also integrates with tools like Datashader and HoloViews to enable visualization of truly massive datasets.

Bokeh vs. Other Visualization Libraries

Python has a rich ecosystem of visualization libraries, each with its own strengths and use cases. So how does Bokeh compare to some of the other popular options?

  • vs. Matplotlib: Bokeh is more focused on web-based interactive visualizations, while Matplotlib is better for generating static publication-quality figures. Bokeh also generally requires less code than Matplotlib for basic plots.

  • vs. Plotly: Bokeh and Plotly are quite similar in their goals and capabilities. Plotly has a larger user base and more name recognition, but Bokeh tends to be more customizable.

  • vs. Altair: Altair is a newer declarative plotting library based on Vega and Vega-Lite. It has a more streamlined API than Bokeh, but is less mature and has fewer built-in chart types.

Ultimately, the "best" library depends on the specific needs of your project. However, Bokeh is a great all-around choice, especially for web-based interactive dashboards and applications.

The Future of Bokeh

Bokeh has come a long way since its initial release in 2013, but the developers aren‘t resting on their laurels. The Bokeh team is continuously adding new features and improving performance.

Some of the most exciting new developments include:

  • Bokeh Applications: a new way to create full-featured data apps and dashboards with pure Python callbacks
  • Improved Widgets: more tools for adding interactive controls to plots and apps
  • Faster WebGL Rendering: taking advantage of the latest web technologies for even smoother performance

From a broader perspective, the future of visualization in general is trending toward more interactivity, richer experiences, and better tooling to handle the ever-increasing scale of data. Bokeh, with its powerful capabilities and active developer community, is well-positioned to be a leader in this space for years to come.

Conclusion

We‘ve only scratched the surface of what Bokeh can do in this gentle introduction. The core concepts of figures, glyphs, and layouts provide a foundation to build on, but the library is truly vast. To learn more, check out the following resources:

No matter your background or domain, being able to create engaging visualizations is an indispensable skill. And in the Python world, you‘d be hard-pressed to find a better tool for the job than Bokeh. Now go forth and visualize!

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Similar Posts