0
# Input/Output Operations
1
2
Functions for controlling plot output, display, and export across different environments including Jupyter notebooks, standalone HTML files, and image formats. These functions manage how and where Bokeh visualizations are rendered and saved.
3
4
## Capabilities
5
6
### Output Configuration
7
8
Functions for configuring where and how plots are displayed.
9
10
```python { .api }
11
def output_file(filename, title=None, mode=None, root_dir=None):
12
"""
13
Direct output to static HTML file.
14
15
Parameters:
16
- filename: Output filename (with .html extension)
17
- title: HTML document title
18
- mode: 'inline' or 'cdn' for BokehJS resources
19
- root_dir: Root directory for relative paths
20
"""
21
22
def output_notebook(hide_banner=None, load_timeout=5000, notebook_type='jupyter'):
23
"""
24
Direct output to Jupyter notebook.
25
26
Parameters:
27
- hide_banner: Whether to hide Bokeh loading banner
28
- load_timeout: Timeout for loading BokehJS (milliseconds)
29
- notebook_type: 'jupyter', 'zeppelin', or 'databricks'
30
"""
31
32
def reset_output():
33
"""
34
Reset output configuration.
35
36
Clears all previously set output modes.
37
"""
38
```
39
40
### Display Functions
41
42
Functions for showing plots in various environments.
43
44
```python { .api }
45
def show(obj, browser=None, new=None):
46
"""
47
Display plot in browser or notebook.
48
49
Parameters:
50
- obj: Plot object, layout, or application to display
51
- browser: Browser name/path (for file output only)
52
- new: 'tab', 'window', or None for browser behavior
53
54
Behavior depends on current output mode:
55
- File output: Opens HTML file in browser
56
- Notebook output: Displays inline in notebook
57
- No output set: Defaults to file output with temp file
58
"""
59
60
def save(obj, filename=None, resources=None, title=None):
61
"""
62
Save plot to HTML file.
63
64
Parameters:
65
- obj: Plot object, layout, or application to save
66
- filename: Output filename (defaults to current output_file setting)
67
- resources: BokehJS resources ('inline', 'cdn', or Resources object)
68
- title: HTML document title
69
70
Returns:
71
str: Path to saved file
72
"""
73
```
74
75
### Image Export
76
77
Functions for exporting plots as static images.
78
79
```python { .api }
80
def export_png(obj, filename=None, width=None, height=None, webdriver=None, timeout=5):
81
"""
82
Export plot as PNG image.
83
84
Parameters:
85
- obj: Plot object or layout to export
86
- filename: Output filename (with .png extension)
87
- width: Image width in pixels (overrides plot width)
88
- height: Image height in pixels (overrides plot height)
89
- webdriver: Selenium webdriver instance
90
- timeout: Maximum time to wait for rendering (seconds)
91
92
Returns:
93
bytes or None: PNG image data if filename not provided
94
95
Requires:
96
- selenium webdriver (chromedriver, geckodriver, etc.)
97
- pillow library for image processing
98
"""
99
100
def export_svg(obj, filename=None, width=None, height=None, webdriver=None, timeout=5):
101
"""
102
Export plot as SVG image.
103
104
Parameters:
105
- obj: Plot object or layout to export
106
- filename: Output filename (with .svg extension)
107
- width: Image width in pixels
108
- height: Image height in pixels
109
- webdriver: Selenium webdriver instance
110
- timeout: Maximum time to wait for rendering (seconds)
111
112
Returns:
113
str or None: SVG markup if filename not provided
114
"""
115
116
def export_svgs(objs, filename=None, width=None, height=None, webdriver=None, timeout=5):
117
"""
118
Export multiple plots as SVG images.
119
120
Parameters:
121
- objs: List of plot objects to export
122
- filename: Base filename pattern (will append indices)
123
- width: Image width in pixels
124
- height: Image height in pixels
125
- webdriver: Selenium webdriver instance
126
- timeout: Maximum time to wait for rendering (seconds)
127
128
Returns:
129
List[str]: SVG markup for each plot if filename not provided
130
"""
131
```
132
133
### Document Management
134
135
Functions for managing the current document context.
136
137
```python { .api }
138
def curdoc():
139
"""
140
Get current document.
141
142
Returns the Document object that is currently active. In standalone
143
scripts, this creates a new document. In server applications, returns
144
the session document.
145
146
Returns:
147
Document: Current document instance
148
"""
149
```
150
151
### Notebook Integration
152
153
Functions for enhanced Jupyter notebook integration.
154
155
```python { .api }
156
def install_notebook_hook(notebook_type='jupyter', load_timeout=5000, hide_banner=None):
157
"""
158
Install notebook display hooks.
159
160
Parameters:
161
- notebook_type: 'jupyter', 'zeppelin', or 'databricks'
162
- load_timeout: Timeout for loading BokehJS
163
- hide_banner: Whether to hide loading banner
164
165
Enables automatic display of plots without explicit show() calls.
166
"""
167
168
def push_notebook(handle=None):
169
"""
170
Push updated plot data to notebook.
171
172
Parameters:
173
- handle: CommsHandle from previous push_notebook call
174
175
Returns:
176
CommsHandle: Handle for future updates
177
178
Used for live updates of plots in notebooks without full re-rendering.
179
"""
180
```
181
182
### Resource Management
183
184
Advanced functions for controlling how BokehJS resources are included.
185
186
```python { .api }
187
class Resources:
188
"""Controls how BokehJS resources are included."""
189
def __init__(self, mode='inline', version=None, root_dir=None,
190
minified=True, log_level='info', root_url=None):
191
"""
192
Parameters:
193
- mode: 'inline', 'cdn', 'server', 'server-dev'
194
- version: Specific Bokeh version for CDN resources
195
- root_dir: Root directory for relative paths
196
- minified: Use minified BokehJS files
197
- log_level: JavaScript logging level
198
- root_url: Base URL for server mode
199
"""
200
201
def file_html(models, resources, title=None, template=None, template_variables=None):
202
"""
203
Generate standalone HTML file content.
204
205
Parameters:
206
- models: Plot objects to include
207
- resources: Resources object for BokehJS inclusion
208
- title: HTML document title
209
- template: Custom Jinja2 template
210
- template_variables: Variables for template rendering
211
212
Returns:
213
str: Complete HTML document content
214
"""
215
```
216
217
## Usage Examples
218
219
### Basic File Output
220
221
```python
222
from bokeh.plotting import figure, show, output_file
223
224
# Configure file output
225
output_file("my_plot.html", title="My Dashboard")
226
227
# Create plot
228
p = figure(width=400, height=400, title="Sample Plot")
229
p.line([1, 2, 3, 4], [1, 4, 2, 3])
230
231
# Save and display
232
show(p) # Creates my_plot.html and opens in browser
233
```
234
235
### Notebook Output
236
237
```python
238
from bokeh.plotting import figure, show, output_notebook
239
from bokeh.io import push_notebook
240
import numpy as np
241
242
# Enable notebook output
243
output_notebook()
244
245
# Create plot with data
246
x = np.linspace(0, 4*np.pi, 100)
247
y = np.sin(x)
248
p = figure(width=600, height=300)
249
line = p.line(x, y)
250
251
# Show with push handle for updates
252
handle = show(p, notebook_handle=True)
253
254
# Update data dynamically
255
for i in range(10):
256
y = np.sin(x + i/10)
257
line.data_source.data = {'x': x, 'y': y}
258
push_notebook(handle=handle)
259
time.sleep(0.5)
260
```
261
262
### Image Export
263
264
```python
265
from bokeh.plotting import figure, output_file
266
from bokeh.io import export_png, export_svg
267
import numpy as np
268
269
# Create plot
270
p = figure(width=600, height=400, title="Export Example")
271
x = np.linspace(0, 4*np.pi, 100)
272
p.line(x, np.sin(x), line_width=2)
273
p.circle(x[::10], np.sin(x[::10]), size=10, color='red')
274
275
# Export as PNG (requires selenium + webdriver)
276
export_png(p, filename="plot.png")
277
278
# Export as SVG
279
export_svg(p, filename="plot.svg")
280
281
# Export with custom dimensions
282
export_png(p, filename="plot_large.png", width=1200, height=800)
283
```
284
285
### Multiple Output Modes
286
287
```python
288
from bokeh.plotting import figure, show, save, output_file, output_notebook
289
290
# Create plot
291
p = figure(width=400, height=400)
292
p.scatter([1, 2, 3, 4], [1, 4, 2, 3], size=20)
293
294
# Save to specific file
295
save(p, filename="scatter.html", title="Scatter Plot")
296
297
# Also display in notebook if available
298
try:
299
output_notebook()
300
show(p)
301
except:
302
# Fallback to file output
303
output_file("fallback.html")
304
show(p)
305
```
306
307
### Custom HTML Generation
308
309
```python
310
from bokeh.plotting import figure
311
from bokeh.io import file_html
312
from bokeh.resources import CDN
313
from bokeh.embed import components
314
315
# Create plot
316
p = figure(width=400, height=400)
317
p.line([1, 2, 3, 4], [1, 4, 2, 3])
318
319
# Generate standalone HTML
320
html = file_html(p, CDN, title="Custom HTML")
321
with open("custom.html", "w") as f:
322
f.write(html)
323
324
# Alternative: Generate components for embedding
325
script, div = components(p)
326
print("JavaScript:", script)
327
print("HTML div:", div)
328
```
329
330
### Batch Export
331
332
```python
333
from bokeh.plotting import figure
334
from bokeh.io import export_svgs
335
import numpy as np
336
337
# Create multiple plots
338
plots = []
339
for i in range(5):
340
p = figure(width=300, height=300, title=f"Plot {i+1}")
341
x = np.linspace(0, 4*np.pi, 50)
342
y = np.sin(x + i)
343
p.line(x, y, line_width=2)
344
plots.append(p)
345
346
# Export all plots as SVG
347
export_svgs(plots, filename="batch_plot")
348
# Creates: batch_plot_0.svg, batch_plot_1.svg, ..., batch_plot_4.svg
349
```
350
351
### Server Application Output
352
353
```python
354
from bokeh.io import curdoc
355
from bokeh.plotting import figure
356
from bokeh.models import Button
357
from bokeh.layouts import column
358
359
def update_plot():
360
"""Callback for server application."""
361
# Update plot data
362
p.line([1, 2, 3], [3, 1, 2], color='red')
363
364
# Create plot and button
365
p = figure(width=400, height=400)
366
p.line([1, 2, 3], [1, 2, 3])
367
368
button = Button(label="Update")
369
button.on_click(update_plot)
370
371
# Add to current document (server context)
372
layout = column(button, p)
373
curdoc().add_root(layout)
374
curdoc().title = "Server App"
375
```