定义:
Bokeh 是一个用于构建交互式数据可视化的 Python 库,专注于在 Web 浏览器中呈现动态、可交互的图表。它支持从简单折线图到复杂仪表盘的创建,并提供丰富的交互功能(如缩放、悬停提示、点选筛选等),适合数据探索、实时数据监控及 Web 应用集成。
核心模块与函数
绘图接口(
bokeh.plotting
)
figure()
:创建基础绘图对象,定义画布尺寸、标题、坐标轴范围等。
line()
/circle()
/bar()
:绘制折线图、散点图、柱状图等基本图形。
show()
:显示图表(需配合输出模式设置)。
output_file()
/output_notebook()
:指定输出为 HTML 文件或 Jupyter Notebook。
from bokeh.plotting import figure, show, output_file
output_file("line_plot.html") # 输出到 HTML 文件
p = figure(title="Simple Line Plot", x_axis_label="X", y_axis_label="Y")
p.line([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], line_width=2)
show(p)
交互工具(
bokeh.models
)
工具类型:
PanTool
/WheelZoomTool
:平移、滚轮缩放。
HoverTool
:悬停显示数据详情。
BoxSelectTool
/LassoSelectTool
:框选或套索选择数据点。工具集成:
p = figure(tools="pan, wheel_zoom, box_select, hover")
布局与组件(
bokeh.layouts
)
row()
/column()
:横向或纵向排列多个图表。
gridplot()
:创建网格布局。
Panel()
/Tabs()
:构建选项卡式多页面视图。
from bokeh.layouts import row
p1 = figure(...) # 图表1
p2 = figure(...) # 图表2
layout = row(p1, p2)
show(layout)
数据源与回调(
bokeh.models.sources
)
ColumnDataSource
:高效数据容器,支持动态更新。回调函数:通过
CustomJS
或 Python 回调实现交互逻辑。
from bokeh.models import ColumnDataSource, CustomJS
source = ColumnDataSource(data={"x": [1,2,3], "y": [4,5,6]})
p.circle(x="x", y="y", source=source)
# 添加 JavaScript 回调
source.selected.js_on_change("indices", CustomJS(code="console.log('Selected indices:', cb_data.indices)"))
服务器应用(
bokeh.server
)
创建实时更新的 Web 应用,支持多用户交互。
示例:动态股票行情仪表盘、实时传感器数据监控。
Bokeh 的核心优势
-
交互性:内置丰富的交互工具,无需额外编码即可实现用户与图表的动态交互。
-
高性能:支持大规模数据集渲染(如百万级数据点),通过 WebGL 加速图形绘制。
-
跨平台:输出为 HTML/JS,可在浏览器、Jupyter Notebook、Flask/Django 等 Web 框架中无缝集成。
-
灵活性:提供低级(
bokeh.models
)和高级(bokeh.plotting
)API,满足从快速原型到复杂定制需求。
Bokeh 与 Matplotlib/Seaborn 的对比
特性 | Bokeh | Matplotlib/Seaborn |
---|---|---|
交互性 | 原生支持复杂交互(如悬停、选择) | 有限交互(依赖额外插件如 mpld3 ) |
输出环境 | 专为 Web 设计(HTML/JS) | 静态图片或简单动态图(嵌入 GUI/Web) |
学习曲线 | 较陡峭(需理解 Web 技术栈) | 较平缓(适合传统绘图场景) |
适用场景 | 实时仪表盘、Web 应用 | 科研论文、快速数据探索 |
实战示例:带悬停提示的散点图
from bokeh.plotting import figure, show
from bokeh.models import HoverTool
from bokeh.sampledata.iris import flowers
# 配置悬停提示内容
hover = HoverTool(tooltips=[
("Species", "@species"),
("Petal Length", "@petal_length"),
("Sepal Width", "@sepal_width")
])
# 创建绘图对象
p = figure(title="Iris Dataset", tools=[hover, "pan, wheel_zoom"])
p.circle(
x="petal_length",
y="sepal_width",
source=flowers,
fill_alpha=0.2,
size=10,
legend_field="species"
)
show(p)
常见问题与解决方案
-
图表未显示:
-
确保调用
output_file()
或output_notebook()
。 -
在 Jupyter 中需使用
show(p, notebook_handle=True)
。
-
-
数据更新延迟:
-
使用
ColumnDataSource
并调用source.stream(new_data)
或source.patch(updates)
。
-
-
性能优化:
-
对大数据集启用 WebGL 渲染:
p = figure(output_backend="webgl")
。 -
简化数据(如采样或聚合)。
-
总结
Bokeh 是构建交互式 Web 可视化的强大工具,尤其适合需要动态交互和实时更新的场景。通过其分层 API,用户既能快速生成基础图表,也能深度定制复杂应用。对于 Web 开发者或数据工程师,Bokeh 是实现数据驱动应用的核心利器。