Interactive plots and applications in the browser from Python
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
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.
Functions for configuring where and how plots are displayed.
def output_file(filename, title=None, mode=None, root_dir=None):
"""
Direct output to static HTML file.
Parameters:
- filename: Output filename (with .html extension)
- title: HTML document title
- mode: 'inline' or 'cdn' for BokehJS resources
- root_dir: Root directory for relative paths
"""
def output_notebook(hide_banner=None, load_timeout=5000, notebook_type='jupyter'):
"""
Direct output to Jupyter notebook.
Parameters:
- hide_banner: Whether to hide Bokeh loading banner
- load_timeout: Timeout for loading BokehJS (milliseconds)
- notebook_type: 'jupyter', 'zeppelin', or 'databricks'
"""
def reset_output():
"""
Reset output configuration.
Clears all previously set output modes.
"""Functions for showing plots in various environments.
def show(obj, browser=None, new=None):
"""
Display plot in browser or notebook.
Parameters:
- obj: Plot object, layout, or application to display
- browser: Browser name/path (for file output only)
- new: 'tab', 'window', or None for browser behavior
Behavior depends on current output mode:
- File output: Opens HTML file in browser
- Notebook output: Displays inline in notebook
- No output set: Defaults to file output with temp file
"""
def save(obj, filename=None, resources=None, title=None):
"""
Save plot to HTML file.
Parameters:
- obj: Plot object, layout, or application to save
- filename: Output filename (defaults to current output_file setting)
- resources: BokehJS resources ('inline', 'cdn', or Resources object)
- title: HTML document title
Returns:
str: Path to saved file
"""Functions for exporting plots as static images.
def export_png(obj, filename=None, width=None, height=None, webdriver=None, timeout=5):
"""
Export plot as PNG image.
Parameters:
- obj: Plot object or layout to export
- filename: Output filename (with .png extension)
- width: Image width in pixels (overrides plot width)
- height: Image height in pixels (overrides plot height)
- webdriver: Selenium webdriver instance
- timeout: Maximum time to wait for rendering (seconds)
Returns:
bytes or None: PNG image data if filename not provided
Requires:
- selenium webdriver (chromedriver, geckodriver, etc.)
- pillow library for image processing
"""
def export_svg(obj, filename=None, width=None, height=None, webdriver=None, timeout=5):
"""
Export plot as SVG image.
Parameters:
- obj: Plot object or layout to export
- filename: Output filename (with .svg extension)
- width: Image width in pixels
- height: Image height in pixels
- webdriver: Selenium webdriver instance
- timeout: Maximum time to wait for rendering (seconds)
Returns:
str or None: SVG markup if filename not provided
"""
def export_svgs(objs, filename=None, width=None, height=None, webdriver=None, timeout=5):
"""
Export multiple plots as SVG images.
Parameters:
- objs: List of plot objects to export
- filename: Base filename pattern (will append indices)
- width: Image width in pixels
- height: Image height in pixels
- webdriver: Selenium webdriver instance
- timeout: Maximum time to wait for rendering (seconds)
Returns:
List[str]: SVG markup for each plot if filename not provided
"""Functions for managing the current document context.
def curdoc():
"""
Get current document.
Returns the Document object that is currently active. In standalone
scripts, this creates a new document. In server applications, returns
the session document.
Returns:
Document: Current document instance
"""Functions for enhanced Jupyter notebook integration.
def install_notebook_hook(notebook_type='jupyter', load_timeout=5000, hide_banner=None):
"""
Install notebook display hooks.
Parameters:
- notebook_type: 'jupyter', 'zeppelin', or 'databricks'
- load_timeout: Timeout for loading BokehJS
- hide_banner: Whether to hide loading banner
Enables automatic display of plots without explicit show() calls.
"""
def push_notebook(handle=None):
"""
Push updated plot data to notebook.
Parameters:
- handle: CommsHandle from previous push_notebook call
Returns:
CommsHandle: Handle for future updates
Used for live updates of plots in notebooks without full re-rendering.
"""Advanced functions for controlling how BokehJS resources are included.
class Resources:
"""Controls how BokehJS resources are included."""
def __init__(self, mode='inline', version=None, root_dir=None,
minified=True, log_level='info', root_url=None):
"""
Parameters:
- mode: 'inline', 'cdn', 'server', 'server-dev'
- version: Specific Bokeh version for CDN resources
- root_dir: Root directory for relative paths
- minified: Use minified BokehJS files
- log_level: JavaScript logging level
- root_url: Base URL for server mode
"""
def file_html(models, resources, title=None, template=None, template_variables=None):
"""
Generate standalone HTML file content.
Parameters:
- models: Plot objects to include
- resources: Resources object for BokehJS inclusion
- title: HTML document title
- template: Custom Jinja2 template
- template_variables: Variables for template rendering
Returns:
str: Complete HTML document content
"""from bokeh.plotting import figure, show, output_file
# Configure file output
output_file("my_plot.html", title="My Dashboard")
# Create plot
p = figure(width=400, height=400, title="Sample Plot")
p.line([1, 2, 3, 4], [1, 4, 2, 3])
# Save and display
show(p) # Creates my_plot.html and opens in browserfrom bokeh.plotting import figure, show, output_notebook
from bokeh.io import push_notebook
import numpy as np
# Enable notebook output
output_notebook()
# Create plot with data
x = np.linspace(0, 4*np.pi, 100)
y = np.sin(x)
p = figure(width=600, height=300)
line = p.line(x, y)
# Show with push handle for updates
handle = show(p, notebook_handle=True)
# Update data dynamically
for i in range(10):
y = np.sin(x + i/10)
line.data_source.data = {'x': x, 'y': y}
push_notebook(handle=handle)
time.sleep(0.5)from bokeh.plotting import figure, output_file
from bokeh.io import export_png, export_svg
import numpy as np
# Create plot
p = figure(width=600, height=400, title="Export Example")
x = np.linspace(0, 4*np.pi, 100)
p.line(x, np.sin(x), line_width=2)
p.circle(x[::10], np.sin(x[::10]), size=10, color='red')
# Export as PNG (requires selenium + webdriver)
export_png(p, filename="plot.png")
# Export as SVG
export_svg(p, filename="plot.svg")
# Export with custom dimensions
export_png(p, filename="plot_large.png", width=1200, height=800)from bokeh.plotting import figure, show, save, output_file, output_notebook
# Create plot
p = figure(width=400, height=400)
p.scatter([1, 2, 3, 4], [1, 4, 2, 3], size=20)
# Save to specific file
save(p, filename="scatter.html", title="Scatter Plot")
# Also display in notebook if available
try:
output_notebook()
show(p)
except:
# Fallback to file output
output_file("fallback.html")
show(p)from bokeh.plotting import figure
from bokeh.io import file_html
from bokeh.resources import CDN
from bokeh.embed import components
# Create plot
p = figure(width=400, height=400)
p.line([1, 2, 3, 4], [1, 4, 2, 3])
# Generate standalone HTML
html = file_html(p, CDN, title="Custom HTML")
with open("custom.html", "w") as f:
f.write(html)
# Alternative: Generate components for embedding
script, div = components(p)
print("JavaScript:", script)
print("HTML div:", div)from bokeh.plotting import figure
from bokeh.io import export_svgs
import numpy as np
# Create multiple plots
plots = []
for i in range(5):
p = figure(width=300, height=300, title=f"Plot {i+1}")
x = np.linspace(0, 4*np.pi, 50)
y = np.sin(x + i)
p.line(x, y, line_width=2)
plots.append(p)
# Export all plots as SVG
export_svgs(plots, filename="batch_plot")
# Creates: batch_plot_0.svg, batch_plot_1.svg, ..., batch_plot_4.svgfrom bokeh.io import curdoc
from bokeh.plotting import figure
from bokeh.models import Button
from bokeh.layouts import column
def update_plot():
"""Callback for server application."""
# Update plot data
p.line([1, 2, 3], [3, 1, 2], color='red')
# Create plot and button
p = figure(width=400, height=400)
p.line([1, 2, 3], [1, 2, 3])
button = Button(label="Update")
button.on_click(update_plot)
# Add to current document (server context)
layout = column(button, p)
curdoc().add_root(layout)
curdoc().title = "Server App"