or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

client-server.mdcolors-transforms.mdcommand-line.mddocument-management.mdembedding-integration.mdevents-interactivity.mdindex.mdio-operations.mdlayouts.mdmodels-data-sources.mdplotting-interface.mdserver-applications.mdwidgets.md
tile.json

tessl/pypi-bokeh

Interactive plots and applications in the browser from Python

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/bokeh@3.8.x

To install, run

npx @tessl/cli install tessl/pypi-bokeh@3.8.0

index.mddocs/

Bokeh

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.

Package Information

  • Package Name: bokeh
  • Language: Python
  • Installation: pip install bokeh

Core Imports

import bokeh

Common for creating plots:

from bokeh.plotting import figure, show, save, output_file, output_notebook

For interactive applications:

from bokeh.plotting import figure, show, curdoc
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import Button, Slider, TextInput
from bokeh.layouts import column, row

For server applications:

from bokeh.application import Application
from bokeh.application.handlers import FunctionHandler
from bokeh.server.server import Server
from bokeh.io import curdoc

For data visualization:

from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource, HoverTool
from bokeh.transform import factor_cmap, linear_cmap, stack, dodge
from bokeh.palettes import Category10, Viridis256

Basic Usage

from bokeh.plotting import figure, show, output_file
import numpy as np

# Prepare data
x = np.linspace(0, 4*np.pi, 100)
y = np.sin(x)

# Create a new plot with tools
p = figure(title="Simple line example", x_axis_label='x', y_axis_label='y',
           width=400, height=400)

# Add a line renderer with legend and line thickness
p.line(x, y, legend_label="sin(x)", line_width=2)

# Output to static HTML file
output_file("line.html")

# Show the result
show(p)

Create interactive scatter plot:

from bokeh.plotting import figure, show
from bokeh.models import HoverTool

# Sample data
x = [1, 2, 3, 4, 5]
y = [6, 7, 2, 4, 5]
colors = ["red", "green", "blue", "orange", "purple"]

# Create figure with hover tool
p = figure(title="Interactive Scatter Plot", tools="pan,wheel_zoom,box_zoom,reset,save",
           tooltips=[("(X,Y)", "($x, $y)")])

# Add circle markers
p.circle(x, y, size=20, color=colors, alpha=0.6)

show(p)

Architecture

Bokeh's architecture is built on several key components:

  • Document Model: Central container (Document) that holds all models and manages their state
  • Model System: Object-oriented hierarchy where every visual element is a Model subclass
  • Plotting Interface: High-level figure() API that simplifies common plotting tasks
  • Glyph System: Low-level drawing primitives for all visual elements (lines, circles, rectangles, etc.)
  • Data Sources: ColumnDataSource and other data containers that feed data to glyphs
  • Server Framework: Optional server component for building interactive applications with Python callbacks

This design enables both simple static plots and complex interactive applications while maintaining a consistent programming model throughout.

Capabilities

High-Level Plotting Interface

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.

def figure(x_range=None, y_range=None, width=600, height=600, title=None, tools=None, **kwargs):
    """Create a new Figure for plotting."""

def show(obj, browser=None, new=None):
    """Display plot in browser or notebook."""

def save(obj, filename=None, **kwargs):
    """Save plot to HTML file."""

DEFAULT_TOOLS: str  # "pan,wheel_zoom,box_zoom,save,reset,help"

Plotting Interface

Model System and Data Sources

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.

class Model:
    """Base class for all Bokeh models."""

class ColumnDataSource(Model):
    """Primary data source for Bokeh plots."""
    def __init__(self, data=None, **kwargs): ...

class Document:
    """Container for all Bokeh models."""
    def add_root(self, model): ...
    def remove_root(self, model): ...

Models and Data Sources

Input/Output and Display

Functions for controlling plot output, export, and display across different environments including Jupyter notebooks, standalone HTML files, and PNG/SVG export.

def output_file(filename, title=None, mode=None, root_dir=None):
    """Direct output to HTML file."""

def output_notebook(hide_banner=None, load_timeout=5000, notebook_type='jupyter'):
    """Direct output to Jupyter notebook."""

def export_png(obj, filename=None, **kwargs):
    """Export plot as PNG image."""

def export_svg(obj, filename=None, **kwargs):
    """Export plot as SVG."""

def curdoc():
    """Get current document."""

Input/Output Operations

Layout System

Functions and classes for arranging multiple plots and widgets into complex layouts including grids, rows, columns, and nested arrangements.

def row(*children, **kwargs):
    """Arrange plots/widgets horizontally."""

def column(*children, **kwargs):
    """Arrange plots/widgets vertically."""

def gridplot(children, **kwargs):
    """Create grid of plots with shared tools."""

class Spacer:
    """Empty space for layouts."""

Layouts

Colors and Data Transforms

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.

def linear_cmap(field_name, palette, low, high, **kwargs):
    """Linear color mapping transformation."""

def factor_cmap(field_name, palette, factors, **kwargs):
    """Categorical color mapping."""

def stack(*fields):
    """Stack transformation for bar charts."""

def dodge(field_name, value, range=None):
    """Dodge transformation for categorical data."""

# Color classes
class RGB:
    def __init__(self, r: int, g: int, b: int, a: float = 1.0): ...

class HSL:
    def __init__(self, h: float, s: float, l: float, a: float = 1.0): ...

Colors and Transforms

Events and Interactivity

Event system for building interactive applications. Provides 30+ event types for user interactions including mouse events, keyboard events, plot events, and custom events.

class Event:
    """Base event class."""

class PlotEvent(Event):
    """Plot-specific events."""

class PointEvent(PlotEvent):
    """Events with x/y coordinates."""
    x: float
    y: float

# Specific event types
class Tap(PointEvent): ...
class DoubleTap(PointEvent): ...
class MouseMove(PointEvent): ...
class Pan(PointEvent): ...

Events and Interactivity

Embedding and Integration

Functions for embedding Bokeh plots in web pages, generating standalone HTML, and integrating with web frameworks and content management systems.

def components(plot_objects, wrap_script=True, wrap_plot_info=True):
    """Generate HTML components for embedding."""

def file_html(models, resources, title=None, **kwargs):
    """Generate standalone HTML file content."""

def json_item(model, target=None):
    """Generate JSON representation for embedding."""

def autoload_static(model, resources, script_path):
    """Generate script for static embedding."""

Embedding and Integration

Server and Interactive Applications

Framework for building interactive web applications with Python callbacks. Enables real-time data updates, user interaction handling, and complex application logic entirely in Python.

class Application:
    """Bokeh application factory."""
    def __init__(self, *handlers, **kwargs): ...

def curdoc():
    """Get current document for server applications."""

# Client functions
def push_session(session):
    """Push session to server."""

def pull_session(session_id=None, url=None, io_loop=None):
    """Pull session from server."""

class ClientSession:
    """Client session for server connection."""

Server and Applications

Interactive Widgets

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.

class Button:
    """Standard push button widget."""
    def __init__(self, label="Button", button_type="default", **kwargs): ...

class Slider:
    """Single-value slider widget."""  
    def __init__(self, start=0, end=1, value=0.5, step=0.1, title=None, **kwargs): ...

class TextInput:
    """Single-line text input field."""
    def __init__(self, value="", title=None, placeholder="", **kwargs): ...

class DataTable:
    """Interactive data table widget."""
    def __init__(self, source=None, columns=None, width=600, height=400, **kwargs): ...

Widgets

Client and Server Framework

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.

class Application:
    """Factory for creating Bokeh documents with handlers."""
    def __init__(self, *handlers, **kwargs): ...

class ClientSession:
    """Client session for server connection."""
    def __init__(self, session_id=None, websocket_url=None, **kwargs): ...

def pull_session(session_id=None, url=None, io_loop=None):
    """Pull an existing session from a Bokeh server."""

def push_session(document, session_id=None, url=None, io_loop=None):
    """Push a document to create a new server session."""

Client and Server

Document Management

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.

class Document:
    """Central container for all Bokeh models in an application."""
    def __init__(self, **kwargs): ...
    def add_root(self, model): ...
    def remove_root(self, model): ...
    def add_periodic_callback(self, callback, period_milliseconds): ...

def without_document_lock(func):
    """Decorator to execute function without document lock."""

DEFAULT_TITLE: str  # "Bokeh Application"

Document Management

Command Line Interface

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.

bokeh serve [OPTIONS] [FILES_OR_DIRS]...    # Serve Bokeh applications
bokeh json [OPTIONS] [FILES]...             # Generate JSON output
bokeh static [OPTIONS] [DIRECTORY]          # Build static content
bokeh build [OPTIONS]                       # Build applications
bokeh init [OPTIONS] [DIRECTORY]            # Initialize projects
bokeh settings [SUBCOMMAND]                 # Manage settings
bokeh secret [SUBCOMMAND]                   # Manage secrets

Command Line Interface

Common Data Types

# Core data types used throughout Bokeh
ColumnDataSource = Dict[str, List[Any]]  # Data container
ColorLike = Union[str, RGB, HSL]  # Color specification
Range = Union[Range1d, DataRange1d, FactorRange]  # Axis ranges
ToolsLike = Union[str, List[Tool]]  # Tool specification

class Range1d:
    """Explicit numeric range."""
    def __init__(self, start=None, end=None, **kwargs): ...

class DataRange1d:
    """Automatic numeric range from data."""
    def __init__(self, **kwargs): ...

class FactorRange:
    """Categorical range."""
    def __init__(self, factors=None, **kwargs): ...