0
# Bokeh
1
2
Bokeh is a comprehensive Python library for creating elegant, interactive visualizations for modern web browsers. It enables Python developers to build rich, interactive plots, dashboards, and data applications that run in browsers without requiring JavaScript expertise. Bokeh excels at large-scale data visualization, real-time streaming data, and building interactive web applications directly from Python.
3
4
## Package Information
5
6
- **Package Name**: bokeh
7
- **Language**: Python
8
- **Installation**: `pip install bokeh`
9
10
## Core Imports
11
12
```python
13
import bokeh
14
```
15
16
Common for creating plots:
17
18
```python
19
from bokeh.plotting import figure, show, save, output_file, output_notebook
20
```
21
22
For interactive applications:
23
24
```python
25
from bokeh.plotting import figure, show, curdoc
26
from bokeh.models import ColumnDataSource
27
from bokeh.models.widgets import Button, Slider, TextInput
28
from bokeh.layouts import column, row
29
```
30
31
For server applications:
32
33
```python
34
from bokeh.application import Application
35
from bokeh.application.handlers import FunctionHandler
36
from bokeh.server.server import Server
37
from bokeh.io import curdoc
38
```
39
40
For data visualization:
41
42
```python
43
from bokeh.plotting import figure, show
44
from bokeh.models import ColumnDataSource, HoverTool
45
from bokeh.transform import factor_cmap, linear_cmap, stack, dodge
46
from bokeh.palettes import Category10, Viridis256
47
```
48
49
## Basic Usage
50
51
```python
52
from bokeh.plotting import figure, show, output_file
53
import numpy as np
54
55
# Prepare data
56
x = np.linspace(0, 4*np.pi, 100)
57
y = np.sin(x)
58
59
# Create a new plot with tools
60
p = figure(title="Simple line example", x_axis_label='x', y_axis_label='y',
61
width=400, height=400)
62
63
# Add a line renderer with legend and line thickness
64
p.line(x, y, legend_label="sin(x)", line_width=2)
65
66
# Output to static HTML file
67
output_file("line.html")
68
69
# Show the result
70
show(p)
71
```
72
73
Create interactive scatter plot:
74
75
```python
76
from bokeh.plotting import figure, show
77
from bokeh.models import HoverTool
78
79
# Sample data
80
x = [1, 2, 3, 4, 5]
81
y = [6, 7, 2, 4, 5]
82
colors = ["red", "green", "blue", "orange", "purple"]
83
84
# Create figure with hover tool
85
p = figure(title="Interactive Scatter Plot", tools="pan,wheel_zoom,box_zoom,reset,save",
86
tooltips=[("(X,Y)", "($x, $y)")])
87
88
# Add circle markers
89
p.circle(x, y, size=20, color=colors, alpha=0.6)
90
91
show(p)
92
```
93
94
## Architecture
95
96
Bokeh's architecture is built on several key components:
97
98
- **Document Model**: Central container (`Document`) that holds all models and manages their state
99
- **Model System**: Object-oriented hierarchy where every visual element is a `Model` subclass
100
- **Plotting Interface**: High-level `figure()` API that simplifies common plotting tasks
101
- **Glyph System**: Low-level drawing primitives for all visual elements (lines, circles, rectangles, etc.)
102
- **Data Sources**: `ColumnDataSource` and other data containers that feed data to glyphs
103
- **Server Framework**: Optional server component for building interactive applications with Python callbacks
104
105
This design enables both simple static plots and complex interactive applications while maintaining a consistent programming model throughout.
106
107
## Capabilities
108
109
### High-Level Plotting Interface
110
111
The primary interface for creating interactive visualizations. The `figure()` function creates plot containers with 70+ glyph methods for different chart types, built-in tools for interaction, and automatic legend/axis management.
112
113
```python { .api }
114
def figure(x_range=None, y_range=None, width=600, height=600, title=None, tools=None, **kwargs):
115
"""Create a new Figure for plotting."""
116
117
def show(obj, browser=None, new=None):
118
"""Display plot in browser or notebook."""
119
120
def save(obj, filename=None, **kwargs):
121
"""Save plot to HTML file."""
122
123
DEFAULT_TOOLS: str # "pan,wheel_zoom,box_zoom,save,reset,help"
124
```
125
126
[Plotting Interface](./plotting-interface.md)
127
128
### Model System and Data Sources
129
130
Low-level building blocks for all Bokeh visualizations. The model system provides 200+ classes for glyphs, tools, widgets, layouts, data sources, and rendering components. Essential for custom visualizations and advanced use cases.
131
132
```python { .api }
133
class Model:
134
"""Base class for all Bokeh models."""
135
136
class ColumnDataSource(Model):
137
"""Primary data source for Bokeh plots."""
138
def __init__(self, data=None, **kwargs): ...
139
140
class Document:
141
"""Container for all Bokeh models."""
142
def add_root(self, model): ...
143
def remove_root(self, model): ...
144
```
145
146
[Models and Data Sources](./models-data-sources.md)
147
148
### Input/Output and Display
149
150
Functions for controlling plot output, export, and display across different environments including Jupyter notebooks, standalone HTML files, and PNG/SVG export.
151
152
```python { .api }
153
def output_file(filename, title=None, mode=None, root_dir=None):
154
"""Direct output to HTML file."""
155
156
def output_notebook(hide_banner=None, load_timeout=5000, notebook_type='jupyter'):
157
"""Direct output to Jupyter notebook."""
158
159
def export_png(obj, filename=None, **kwargs):
160
"""Export plot as PNG image."""
161
162
def export_svg(obj, filename=None, **kwargs):
163
"""Export plot as SVG."""
164
165
def curdoc():
166
"""Get current document."""
167
```
168
169
[Input/Output Operations](./io-operations.md)
170
171
### Layout System
172
173
Functions and classes for arranging multiple plots and widgets into complex layouts including grids, rows, columns, and nested arrangements.
174
175
```python { .api }
176
def row(*children, **kwargs):
177
"""Arrange plots/widgets horizontally."""
178
179
def column(*children, **kwargs):
180
"""Arrange plots/widgets vertically."""
181
182
def gridplot(children, **kwargs):
183
"""Create grid of plots with shared tools."""
184
185
class Spacer:
186
"""Empty space for layouts."""
187
```
188
189
[Layouts](./layouts.md)
190
191
### Colors and Data Transforms
192
193
Color palettes and data transformation functions for enhanced visualizations. Includes 100+ built-in color palettes and transforms for categorical mapping, stacking, dodging, and color mapping.
194
195
```python { .api }
196
def linear_cmap(field_name, palette, low, high, **kwargs):
197
"""Linear color mapping transformation."""
198
199
def factor_cmap(field_name, palette, factors, **kwargs):
200
"""Categorical color mapping."""
201
202
def stack(*fields):
203
"""Stack transformation for bar charts."""
204
205
def dodge(field_name, value, range=None):
206
"""Dodge transformation for categorical data."""
207
208
# Color classes
209
class RGB:
210
def __init__(self, r: int, g: int, b: int, a: float = 1.0): ...
211
212
class HSL:
213
def __init__(self, h: float, s: float, l: float, a: float = 1.0): ...
214
```
215
216
[Colors and Transforms](./colors-transforms.md)
217
218
### Events and Interactivity
219
220
Event system for building interactive applications. Provides 30+ event types for user interactions including mouse events, keyboard events, plot events, and custom events.
221
222
```python { .api }
223
class Event:
224
"""Base event class."""
225
226
class PlotEvent(Event):
227
"""Plot-specific events."""
228
229
class PointEvent(PlotEvent):
230
"""Events with x/y coordinates."""
231
x: float
232
y: float
233
234
# Specific event types
235
class Tap(PointEvent): ...
236
class DoubleTap(PointEvent): ...
237
class MouseMove(PointEvent): ...
238
class Pan(PointEvent): ...
239
```
240
241
[Events and Interactivity](./events-interactivity.md)
242
243
### Embedding and Integration
244
245
Functions for embedding Bokeh plots in web pages, generating standalone HTML, and integrating with web frameworks and content management systems.
246
247
```python { .api }
248
def components(plot_objects, wrap_script=True, wrap_plot_info=True):
249
"""Generate HTML components for embedding."""
250
251
def file_html(models, resources, title=None, **kwargs):
252
"""Generate standalone HTML file content."""
253
254
def json_item(model, target=None):
255
"""Generate JSON representation for embedding."""
256
257
def autoload_static(model, resources, script_path):
258
"""Generate script for static embedding."""
259
```
260
261
[Embedding and Integration](./embedding-integration.md)
262
263
### Server and Interactive Applications
264
265
Framework for building interactive web applications with Python callbacks. Enables real-time data updates, user interaction handling, and complex application logic entirely in Python.
266
267
```python { .api }
268
class Application:
269
"""Bokeh application factory."""
270
def __init__(self, *handlers, **kwargs): ...
271
272
def curdoc():
273
"""Get current document for server applications."""
274
275
# Client functions
276
def push_session(session):
277
"""Push session to server."""
278
279
def pull_session(session_id=None, url=None, io_loop=None):
280
"""Pull session from server."""
281
282
class ClientSession:
283
"""Client session for server connection."""
284
```
285
286
[Server and Applications](./server-applications.md)
287
288
### Interactive Widgets
289
290
Comprehensive widget system with 40+ widget types for building interactive data applications. Includes buttons, inputs, sliders, tables, date pickers, and specialized controls that enable rich user interactions with Python callbacks.
291
292
```python { .api }
293
class Button:
294
"""Standard push button widget."""
295
def __init__(self, label="Button", button_type="default", **kwargs): ...
296
297
class Slider:
298
"""Single-value slider widget."""
299
def __init__(self, start=0, end=1, value=0.5, step=0.1, title=None, **kwargs): ...
300
301
class TextInput:
302
"""Single-line text input field."""
303
def __init__(self, value="", title=None, placeholder="", **kwargs): ...
304
305
class DataTable:
306
"""Interactive data table widget."""
307
def __init__(self, source=None, columns=None, width=600, height=400, **kwargs): ...
308
```
309
310
[Widgets](./widgets.md)
311
312
### Client and Server Framework
313
314
Client-server functionality for building interactive web applications with real-time Python callbacks. Enables building standalone Bokeh applications that update dynamically based on user interactions and server-side computations.
315
316
```python { .api }
317
class Application:
318
"""Factory for creating Bokeh documents with handlers."""
319
def __init__(self, *handlers, **kwargs): ...
320
321
class ClientSession:
322
"""Client session for server connection."""
323
def __init__(self, session_id=None, websocket_url=None, **kwargs): ...
324
325
def pull_session(session_id=None, url=None, io_loop=None):
326
"""Pull an existing session from a Bokeh server."""
327
328
def push_session(document, session_id=None, url=None, io_loop=None):
329
"""Push a document to create a new server session."""
330
```
331
332
[Client and Server](./client-server.md)
333
334
### Document Management
335
336
Document model and lifecycle management for Bokeh applications. The Document serves as the central container for all Bokeh models, managing their relationships, state changes, and synchronization between client and server.
337
338
```python { .api }
339
class Document:
340
"""Central container for all Bokeh models in an application."""
341
def __init__(self, **kwargs): ...
342
def add_root(self, model): ...
343
def remove_root(self, model): ...
344
def add_periodic_callback(self, callback, period_milliseconds): ...
345
346
def without_document_lock(func):
347
"""Decorator to execute function without document lock."""
348
349
DEFAULT_TITLE: str # "Bokeh Application"
350
```
351
352
[Document Management](./document-management.md)
353
354
### Command Line Interface
355
356
Comprehensive command-line tools for Bokeh development, deployment, and management. The `bokeh` command provides subcommands for serving applications, building static content, managing configurations, and working with Bokeh projects.
357
358
```bash { .api }
359
bokeh serve [OPTIONS] [FILES_OR_DIRS]... # Serve Bokeh applications
360
bokeh json [OPTIONS] [FILES]... # Generate JSON output
361
bokeh static [OPTIONS] [DIRECTORY] # Build static content
362
bokeh build [OPTIONS] # Build applications
363
bokeh init [OPTIONS] [DIRECTORY] # Initialize projects
364
bokeh settings [SUBCOMMAND] # Manage settings
365
bokeh secret [SUBCOMMAND] # Manage secrets
366
```
367
368
[Command Line Interface](./command-line.md)
369
370
## Common Data Types
371
372
```python { .api }
373
# Core data types used throughout Bokeh
374
ColumnDataSource = Dict[str, List[Any]] # Data container
375
ColorLike = Union[str, RGB, HSL] # Color specification
376
Range = Union[Range1d, DataRange1d, FactorRange] # Axis ranges
377
ToolsLike = Union[str, List[Tool]] # Tool specification
378
379
class Range1d:
380
"""Explicit numeric range."""
381
def __init__(self, start=None, end=None, **kwargs): ...
382
383
class DataRange1d:
384
"""Automatic numeric range from data."""
385
def __init__(self, **kwargs): ...
386
387
class FactorRange:
388
"""Categorical range."""
389
def __init__(self, factors=None, **kwargs): ...
390
```