Using Bokeh for Interactive Scatter and Bar Charts in Python
This tutorial explains how to use the Python Bokeh library to create interactive scatter, bar, and multi‑panel visualizations, covering installation, figure configuration, hover tooltips, data sources, color mapping, looping over categories, and linking plots with shared ranges.
Bokeh is an interactive visualization library for Python that renders graphics in web browsers.
The article introduces Bokeh’s three interface levels—Charts, Plotting, and Models—and demonstrates how to set up the environment by importing required packages.
Typical imports:
import numpy as np<br/>import pandas as pd<br/>import matplotlib.pyplot as plt<br/>%matplotlib inline<br/><br/>import warnings<br/>warnings.filterwarnings('ignore')Next, the Bokeh modules needed for plotting are imported:
# Import chart‑drawing and display modules<br/>from bokeh.plotting import figure, show<br/><br/># Import notebook utilities and tools<br/>from bokeh.io import output_notebook, output_file, show<br/>from bokeh.models import HoverTool<br/>output_notebook()The library provides three levels of API:
Charts – high‑level, simple statistical plots
Plotting – mid‑level, assemble glyphs
Models – low‑level, full flexibility
A figure can be created with many configurable parameters:
figure(plot_width, plot_height,
tools,
toolbar_location,
x_axis_label, y_axis_label,
x_range, y_range,
title)HoverTool is used to show data values when the cursor hovers over glyphs:
from bokeh.models import HoverTool
hover = HoverTool(tooltips=[
('index', '$index'),
('(x,y)', '($x,$y)'),
('A', '@A'), ('B', '@B'),
('type', '@type'),
('color', '@color')
])Example: drawing a scatter plot with custom size, color, and alpha, using a pandas DataFrame or a ColumnDataSource as the data source.
p = figure(plot_width=600, plot_height=400,
tools=[hover, 'crosshair,pan,box_zoom,save,reset,help'],
toolbar_location='above',
x_axis_label='A', y_axis_label='B',
x_range=[-3, 3], y_range=[-3, 3],
title='测试图表')
p.circle(x='A', y='B', source=df, size=20, alpha=0.5)
show(p)The guide also shows how to set colors and sizes from data columns, create categorical and continuous color maps, and adjust glyph properties such as line_color, fill_color, and fill_alpha.
Looping over a categorical column to generate separate plots:
colors = ['red', 'olive', 'darkred', 'goldenrod', 'skyblue', 'orange', 'salmon']
for t, pi in zip(df['type'].unique()[:3], [p1, p2, p3]):
pi.circle(df['A'][df['type'] == t], df['B'][df['type'] == t],
size=20, alpha=0.5, color=colors[t],
legend='type%i' % t)
show(pi)Bar charts are created with the vbar glyph:
p.vbar(x=[1,2,3], bottom=0, top=[1.2,2.5,3.7],
width=0.5,
color=['red','blue','green'],
alpha=0.8,
line_width=1, line_alpha=0.8,
line_color='black', line_dash=[5,2],
fill_color='red', fill_alpha=0.6)Multiple linked plots can be arranged with gridplot , sharing ranges for coordinated interaction:
from bokeh.layouts import gridplot
s1 = figure(plot_width=250, plot_height=250, tools=[hover, 'crosshair,pan,box_zoom,save,reset,help'], toolbar_location='above')
s1.circle('x', 'y0', source=df, size=10, color='navy', alpha=0.5)
s2 = figure(plot_width=250, plot_height=250, x_range=s1.x_range, y_range=s1.y_range,
tools=[hover, 'crosshair,pan,box_zoom,save,reset,help'], toolbar_location='above')
s2.triangle('x', 'y1', source=df, size=10, color='firebrick', alpha=0.5)
s3 = figure(plot_width=250, plot_height=250,
tools=[hover, 'crosshair,pan,box_zoom,save,reset,help'], toolbar_location='above')
s3.square('x', 'y2', source=df, size=10, color='olive', alpha=0.5)
p = gridplot([[s1, s2, s3]])
show(p)All code snippets are presented in ... blocks to preserve exact syntax, enabling readers to copy and run them directly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.