Cheat Sheet速查表
跳转到主要内容

Bokeh 交互式数据可视化速查表

Bokeh 是专为现代 Web 浏览器打造的高性能 Python 交互式数据可视化库。其核心设计理念是通过 Python 构建富交互图表,并在浏览器端通过 BokehJS 前端渲染引擎直接呈现。

Bokeh 绘图的核心构成公式:

$$\text{画布 (Figure)} + \text{数据源 (ColumnDataSource)} + \text{图元渲染器 (Glyphs)} = \text{交互式可视化}$$

🔗 关联矩阵速查:Pandas 速查表 · NumPy 速查表 · Scikit-Learn 速查表 · 数据分析方法速查表 · Python 速查表


1. 端到端快速上手闭环示例

以下示例演示从创建数据、绑定数据源、绘制折线与散点图元、配置 Hover 交互提示,到输出独立 HTML 的标准完整链路:

from bokeh.plotting import figure, show
from bokeh.io import output_file
from bokeh.models import ColumnDataSource, HoverTool

# 1. 准备数据源
data = {
    'x': [1, 2, 3, 4, 5],
    'y': [6, 7, 2, 4, 8],
    'label': ['A', 'B', 'C', 'D', 'E']
}
source = ColumnDataSource(data=data)

# 2. 创建画布 (Bokeh 3.x 使用 width/height)
p = figure(
    title="温度变化趋势图",
    x_axis_label="时间节点 (Day)",
    y_axis_label="数值 (℃)",
    width=700,
    height=400,
    tools="pan,wheel_zoom,box_zoom,reset,save"
)

# 3. 添加图元 (折线 + 数据点圆圈)
p.line(x='x', y='y', source=source, line_width=2, color="#1f77b4", legend_label="观测值")
circles = p.circle(x='x', y='y', source=source, size=10, fill_color="white", line_color="#1f77b4", line_width=2)

# 4. 挂载悬浮提示工具 (HoverTool)
hover = HoverTool(
    renderers=[circles],
    tooltips=[("样本标签", "@label"), ("时间", "$x{0}"), ("温度", "$y{0.0} ℃")]
)
p.add_tools(hover)

# 5. 指定输出文件并展示
output_file("simple_trend.html", title="Bokeh 趋势图")
show(p)

2. 数据驱动核心:ColumnDataSource

ColumnDataSource(CDS)是 Bokeh 最核心的数据容器。将数据封装为 CDS 能够实现图表间的数据联动、高效客户端更新与动态刷选。

import pandas as pd
from bokeh.models import ColumnDataSource

# 1. 从 Pandas DataFrame 或字典创建
df = pd.DataFrame({
    'mpg': [18.0, 15.0, 18.0, 16.0],
    'hp': [130, 165, 150, 150],
    'origin': ['USA', 'USA', 'USA', 'Europe']
})
source = ColumnDataSource(df)

# 2. 访问内部数据 (字典格式,值为列数据数组)
mpg_values = source.data['mpg']

# 3. 流式动态追加数据 (用于实时监控大屏或 WebSocket 推送)
new_data = {'mpg': [20.0], 'hp': [140], 'origin': ['Japan']}
source.stream(new_data, rollover=1000) # rollover 限制队列最大长度,自动淘汰最旧数据

# 4. 局部补丁更新 (高效原地修改指定行元素,避免全量重绘)
source.patch({
    'hp': [(0, 135)]  # 将索引 0 的 hp 修改为 135
})

3. 画布创建与核心参数(figure())

⚠️ 规范提示:Bokeh 3.0+ 已彻底移除旧版 plot_width 与 plot_height 参数,请统一使用 width 与 height。

from bokeh.plotting import figure

p = figure(
    title="画布标题",
    width=800,                    # 画布宽度 (像素)
    height=500,                   # 画布高度 (像素)
    x_range=(0, 100),             # 手动限制 X 轴显示范围 (或传入分类列表 ['A', 'B', 'C'])
    y_range=(0, 50),
    x_axis_type="datetime",       # 轴类型: "linear", "log", "datetime", "mercator"
    tools="pan,box_zoom,wheel_zoom,reset,save", # 预挂载工具栏
    toolbar_location="right",     # 工具栏位置: "above", "below", "left", "right", None
    background_fill_color="#fafafa"
)

# 坐标轴外观定制
p.xaxis.axis_label = "时间序列"
p.xaxis.axis_label_text_font_size = "12pt"
p.grid.grid_line_dashed = [4, 4] # 网格虚线配置

4. 常用图元(Glyphs)速查表

图元分类方法语法核心参数与说明
散点/圆圈p.circle(x, y, ...)size=10, fill_color, line_color, fill_alpha
方形/矩形p.square(x, y, ...)size, fill_color
通用散点p.scatter(x, y, marker="hex", ...)统一散点接口,marker: 'circle', 'triangle', 'cross', 'star' 等
连续折线p.line(x, y, ...)line_width=2, line_color, line_dash="dashed"
阶梯线p.step(x, y, mode="after", ...)绘制阶梯折线,mode: 'before', 'after', 'center'
多条折线p.multi_line(xs, ys, ...)xs=[[x1, x2], [x3, x4]], ys=[[y1, y2], [y3, y4]] 一次性绘制多条独立曲线
垂直柱状p.vbar(x, width, top, bottom=0)柱状图:x 为柱中心坐标,top 为柱高
水平条形p.hbar(y, height, right, left=0)条形图:y 为条中心坐标,right 为右边界
填充区域p.varea(x, y1, y2, ...)填充区间阴影(如置信区间带、误差带)
多边形面p.patch(x, y, ...)闭合多边形填充

5. 颜色映射与调色板(bokeh.transform)

Bokeh 提供了强大的声明式颜色映射转换函数,支持将数据列直接映射为离散类别色或连续色阶。

5.1 离散分类色彩映射(factor_cmap)

from bokeh.transform import factor_cmap
from bokeh.palettes import Category10

factors = ['USA', 'Asia', 'Europe']
palette = Category10[3] # 取 3 色离散调色板 ['#1f77b4', '#ff7f0e', '#2ca02c']

color_mapping = factor_cmap(
    field_name='origin',
    palette=palette,
    factors=factors
)

p.circle(
    x='mpg', y='hp', source=source,
    color=color_mapping,
    legend_field='origin',  # 根据 origin 字段值自动聚类分组生成图例
    size=9
)

5.2 连续数值渐变映射(linear_cmap & ColorBar)

from bokeh.transform import linear_cmap
from bokeh.palettes import Viridis256
from bokeh.models import ColorBar

mapper = linear_cmap(
    field_name='hp',
    palette=Viridis256,
    low=min(df['hp']),
    high=max(df['hp'])
)

p.circle(x='mpg', y='hp', source=source, color=mapper, size=8)

# 添加侧边颜色条标尺
color_bar = ColorBar(color_mapper=mapper['transform'], width=12, location=(0, 0))
p.add_layout(color_bar, 'right')

6. 交互工具与悬浮提示(HoverTool & 选区状态)

6.1 高级悬停提示配置(HoverTool)

from bokeh.models import HoverTool

hover = HoverTool(
    tooltips=[
        ("车型来源", "@origin"),
        ("百公里油耗", "@mpg{0.0}"),
        ("引擎马力", "@hp 匹"),
        ("屏幕像素坐标", "($sx, $sy)")
    ],
    formatters={
        '@timestamp': 'datetime'  # 指定时间戳列的格式化解析规则
    },
    mode='mouse'                  # 触发模式: 'mouse' (鼠标悬停点) 或 'vline' (垂线穿过)
)
p.add_tools(hover)

6.2 选区状态与高亮样式定制

# 当用户使用 box_select 或 lasso_select 框选时,自动改变选中与未选中样式
p.circle(
    x='mpg', y='hp', source=source,
    size=10,
    color="blue",
    selection_color="red",        # 被框选点高亮为红色
    nonselection_alpha=0.1        # 未被选中点淡化为 0.1 透明度
)

7. 图例控制(Legend)与交互隐藏

⚠️ 规范提示:Bokeh 2.0+ 与 3.x+ 已弃用老式 legend="xxx" 语法。单个标签请使用 legend_label="标签名",按列字段自动分类请使用 legend_field="列名"。

# 1. 常用图例属性设置
p.legend.location = "top_right"          # "top_left", "bottom_right", "center" 等
p.legend.orientation = "horizontal"      # 图例排布方向: "vertical" 或 "horizontal"
p.legend.background_fill_alpha = 0.8
p.legend.border_line_color = "#e0e0e0"

# 2. 交互式隐藏/静音 (用户点击图例时自动隐藏对应图层,极度实用!)
p.legend.click_policy = "hide"           # 可选 "hide" (隐藏) 或 "mute" (变灰淡化)

# 3. 将图例放置在绘图区外部
# 通过 p.add_layout(p.legend[0], 'right') 将图例移出绘图区至右侧空白

8. 多图布局与联动排版(Layouts & Linking)

8.1 行、列与网格布局(row, column, gridplot)

from bokeh.layouts import row, column, gridplot

# 水平行排版
layout_row = row(p1, p2, p3)

# 垂直列排版
layout_col = column(p1, p2)

# 嵌套排版
layout_mix = column(row(p1, p2), p3)

# 2x2 网格排版 (支持 toolbar_location 统一工具栏)
grid = gridplot([[p1, p2], [p3, p4]], width=350, height=300)

8.2 标签页布局(TabPanel & Tabs)

⚠️ 规范提示:Bokeh 3.0+ 已移除旧版 Panel 类(原位于 bokeh.models.widgets),统一重命名为 TabPanel 并直接从 bokeh.models 导入。

from bokeh.models import TabPanel, Tabs

tab1 = TabPanel(child=p1, title="年度营收趋势")
tab2 = TabPanel(child=p2, title="用户增长分布")

tabs_layout = Tabs(tabs=[tab1, tab2])
show(tabs_layout)

8.3 多图联动机制(Linking)

① 坐标轴平移缩放联动(Linked Panning / Zooming)

只需将一个图表的范围对象赋值给另一个图表:

# 缩放平移 p1 时,p2 与 p3 沿 X 轴完全同步变动
p2.x_range = p1.x_range
p3.x_range = p1.x_range

② 联动刷选高亮(Linked Brushing)

多个图表引用同一个 ColumnDataSource 实例即可自动实现联动刷选:

# p1 与 p2 共享同一个 source
p1 = figure(width=350, height=300, tools="box_select,lasso_select,reset")
p1.circle('mpg', 'hp', source=source)

p2 = figure(width=350, height=300, tools="box_select,lasso_select,reset")
p2.circle('mpg', 'weight', source=source)

# 在 p1 中用套索或框选工具选中数据点,p2 对应的数据点会立即高亮联动!
show(row(p1, p2))

9. 输出、嵌入与静态导出

输出目标适用场景核心代码
Jupyter Notebook交互式数据分析与实验探索from bokeh.io import output_notebook, show
output_notebook()
show(p)
独立 HTML 文件离线分享与邮件分发(打包 JS 依赖)from bokeh.io import output_file, save
output_file("chart.html", mode='cdn')
save(p)
Web 页面嵌入嵌入 Django / Flask / FastAPI / Astro 模板from bokeh.embed import components
script, div = components(p)
(前端分别插入 <head> 与 <body>)
静态 PNG 导出插入 PDF 报告或论文(需安装依赖)from bokeh.io import export_png
export_png(p, filename="plot.png")
矢量 SVG 导出高清印刷排版与矢量编辑from bokeh.io import export_svg
p.output_backend = "svg"
export_svg(p, filename="plot.svg")