CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-altair

Vega-Altair: A declarative statistical visualization library for Python.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

rendering-output.mddocs/

Rendering & Output

Display and output options for charts including Jupyter notebook integration, static image export, and HTML generation. Altair provides flexible rendering backends for different environments and use cases.

Capabilities

Renderer Registry

Central registry for managing different rendering backends that control how charts are displayed and exported.

class RendererRegistry:
    def enable(self, name, **kwargs):
        """
        Enable a renderer by name.
        
        Parameters:
        - name: Renderer name ('default', 'html', 'png', 'svg', 'pdf', 'json', 'mimebundle')
        - **kwargs: Renderer-specific options
        """
        
    def register(self, name, renderer_func):
        """
        Register a new renderer function.
        
        Parameters:
        - name: Renderer name
        - renderer_func: Function that renders chart specifications
        """
        
    def get(self):
        """Get current active renderer."""
        
    @property
    def active(self):
        """Get name of active renderer."""
        
    def names(self):
        """Get list of available renderer names."""

# Global renderer registry
renderers = RendererRegistry()

Chart Display Methods

Core methods available on Chart objects for displaying and exporting visualizations.

class Chart:
    def show(self):
        """
        Display chart using the active renderer.
        
        In Jupyter notebooks, displays inline.
        In other environments, may open browser or save file.
        """
        
    def save(
        self,
        filename,
        format=None,
        mode=None,
        vegalite_version=None,
        vega_version=None,
        vegaembed_version=None,
        embed_options=None,
        json_kwds=None,
        webdriver=None,
        scale_factor=1,
        **kwargs
    ):
        """
        Save chart to file in various formats.
        
        Parameters:
        - filename: Output filename with extension
        - format: Output format ('html', 'png', 'svg', 'pdf', 'json')
        - mode: Save mode ('vega-lite' or 'vega')
        - vegalite_version: Vega-Lite version to use
        - vega_version: Vega version to use  
        - vegaembed_version: Vega-Embed version to use
        - embed_options: Vega-Embed configuration options
        - json_kwds: JSON serialization options
        - webdriver: Selenium webdriver for image export
        - scale_factor: Scale factor for image export
        """
        
    def serve(
        self,
        port=8888,
        open=True,
        ip='127.0.0.1',
        n_retries=50,
        files=None,
        jupyter_warning=True,
        inline=False,
        **kwargs
    ):
        """
        Serve chart in local web server.
        
        Parameters:
        - port: Server port number
        - open: Whether to open browser automatically
        - ip: Server IP address
        - n_retries: Number of port retries
        - files: Additional files to serve
        - jupyter_warning: Show Jupyter warning
        - inline: Inline mode for Jupyter
        """
        
    def to_dict(self, validate=True, format='vega-lite', context=None):
        """
        Convert chart to dictionary specification.
        
        Parameters:
        - validate: Whether to validate against schema
        - format: Output format ('vega-lite' or 'vega')
        - context: Conversion context
        
        Returns:
        dict: Chart specification dictionary
        """
        
    def to_json(
        self,
        validate=True,
        indent=2,
        sort_keys=True,
        **kwargs
    ):
        """
        Convert chart to JSON string.
        
        Parameters:
        - validate: Whether to validate against schema
        - indent: JSON indentation
        - sort_keys: Whether to sort dictionary keys
        
        Returns:
        str: JSON representation of chart
        """
        
    def to_html(
        self,
        base_url='https://cdn.jsdelivr.net/npm/',
        output_div='vis',
        embed_options=None,
        json_kwds=None,
        fullhtml=True,
        requirejs=False,
        **kwargs
    ):
        """
        Convert chart to standalone HTML.
        
        Parameters:
        - base_url: Base URL for Vega libraries
        - output_div: HTML div ID for chart
        - embed_options: Vega-Embed options
        - json_kwds: JSON serialization options  
        - fullhtml: Whether to include full HTML document
        - requirejs: Whether to use RequireJS
        
        Returns:
        str: HTML representation of chart
        """

VegaLite Renderer Class

Core renderer class that handles Vega-Lite specification rendering.

class VegaLite:
    def __init__(self, spec, **metadata):
        """
        Vega-Lite renderer for chart specifications.
        
        Parameters:
        - spec: Vega-Lite specification dictionary
        - **metadata: Additional metadata for rendering
        """
        
    def _repr_mimebundle_(self, include=None, exclude=None):
        """Generate MIME bundle for Jupyter display."""
        
    def _repr_html_(self):
        """Generate HTML representation for display."""
        
    @property
    def spec(self):
        """Get chart specification."""

Jupyter Integration

Functions and classes for enhanced Jupyter notebook integration.

class JupyterChart:
    """
    Enhanced chart class with Jupyter-specific capabilities.
    
    Provides interactive widgets and enhanced display options
    for Jupyter notebook environments.
    """
    
    def __init__(self, chart):
        """
        Create JupyterChart from regular Chart.
        
        Parameters:
        - chart: Altair Chart object
        """
        
    def show(self):
        """Display chart with Jupyter optimizations."""
        
    def display(self):
        """Alternative display method for Jupyter."""

def load_ipython_extension(ipython):
    """
    Load Altair IPython extension for magic commands.
    
    Parameters:
    - ipython: IPython instance
    """

Version Constants

Version information for the underlying visualization libraries.

# Library version constants  
VEGA_VERSION: str       # Vega library version
VEGALITE_VERSION: str   # Vega-Lite library version  
VEGAEMBED_VERSION: str  # Vega-Embed library version

# Schema information
SCHEMA_VERSION: str     # Vega-Lite schema version
SCHEMA_URL: str        # URL to Vega-Lite schema

Usage Examples

Basic Display

import altair as alt

chart = alt.Chart(data).mark_circle().encode(
    x='x:Q',
    y='y:Q'
)

# Display in current environment
chart.show()

# In Jupyter notebooks, can also just evaluate
chart  # Displays automatically

Renderer Configuration

# Check available renderers
print(alt.renderers.names())

# Enable specific renderer
alt.renderers.enable('html')
alt.renderers.enable('mimebundle')  # Default for Jupyter

# Check active renderer
print(alt.renderers.active)

Saving Charts

# Save as HTML
chart.save('chart.html')

# Save as PNG (requires selenium and webdriver)
chart.save('chart.png', scale_factor=2)

# Save as SVG
chart.save('chart.svg')

# Save as PDF  
chart.save('chart.pdf')

# Save JSON specification
chart.save('chart.json')

# Save with custom embed options
chart.save(
    'chart.html',
    embed_options={'actions': False, 'theme': 'dark'}
)

HTML Export with Custom Options

# Generate standalone HTML
html_str = chart.to_html(
    embed_options={
        'theme': 'dark',
        'actions': {'export': True, 'source': False, 'compiled': False, 'editor': False}
    },
    fullhtml=True
)

# Write to file
with open('custom_chart.html', 'w') as f:
    f.write(html_str)

JSON Export

# Get dictionary specification
spec_dict = chart.to_dict()

# Get JSON string
json_str = chart.to_json(indent=4)

# Save with validation disabled
spec_dict = chart.to_dict(validate=False)

Local Server

# Serve chart on local server
chart.serve(port=8080, open=True)

# Serve with additional files
chart.serve(
    port=8888,
    files={'data.csv': 'path/to/data.csv'}
)

Jupyter-Specific Features

# Enhanced Jupyter display
jupyter_chart = alt.JupyterChart(chart)
jupyter_chart.show()

# Using magic commands (after loading extension)
# %load_ext altair
# %%altair
# alt.Chart(data).mark_point().encode(x='x:Q', y='y:Q')

Custom Renderer

# Define custom renderer
def custom_png_renderer(spec, **kwargs):
    """Custom PNG renderer with specific settings."""
    # Implementation would handle PNG generation
    # with custom settings
    pass

# Register custom renderer
alt.renderers.register('custom_png', custom_png_renderer)
alt.renderers.enable('custom_png')

Batch Export

# Export multiple charts
charts = [chart1, chart2, chart3]
formats = ['png', 'svg', 'html']

for i, chart in enumerate(charts):
    for fmt in formats:
        filename = f'chart_{i}.{fmt}'
        chart.save(filename)

Advanced HTML Export

# Custom HTML template
html_template = """
<!DOCTYPE html>
<html>
<head>
    <title>Custom Chart</title>
    <style>
        body {{ font-family: Arial, sans-serif; }}
        .chart-container {{ margin: 20px; }}
    </style>
</head>
<body>
    <h1>My Custom Chart</h1>
    <div class="chart-container">
        {chart_html}
    </div>
</body>
</html>
"""

chart_html = chart.to_html(fullhtml=False)
full_html = html_template.format(chart_html=chart_html)

with open('custom_page.html', 'w') as f:
    f.write(full_html)

High-Quality Image Export

# High-DPI image export
chart.save(
    'high_res_chart.png',
    scale_factor=3,  # 3x resolution
    webdriver='chrome'  # Use Chrome webdriver
)

# PDF export with specific settings
chart.save(
    'chart.pdf',
    embed_options={'actions': False},
    scale_factor=2
)

Programmatic Display Control

# Conditional rendering based on environment
import sys

if 'ipykernel' in sys.modules:
    # In Jupyter - use default mimebundle renderer
    alt.renderers.enable('mimebundle')
    chart.show()
elif 'bokeh' in sys.modules:
    # In Bokeh server - use HTML renderer
    alt.renderers.enable('html')
    chart.show()
else:
    # Command line - save to file
    chart.save('output.html')
    print("Chart saved to output.html")

Types

from typing import Union, Dict, Any, Optional, Callable, List

# Renderer function type
RendererFunction = Callable[[Dict[str, Any]], Any]

# Output formats
OutputFormat = Union['html', 'png', 'svg', 'pdf', 'json', 'vega', 'vega-lite']

# Save mode
SaveMode = Union['vega-lite', 'vega']

# Embed options
EmbedOptions = Dict[str, Any]

# MIME bundle
MimeBundle = Dict[str, Any]

# HTML generation options
class HtmlOptions:
    base_url: str = 'https://cdn.jsdelivr.net/npm/'
    output_div: str = 'vis'
    embed_options: Optional[EmbedOptions] = None
    fullhtml: bool = True
    requirejs: bool = False

# Save options
class SaveOptions:
    format: Optional[OutputFormat] = None
    mode: Optional[SaveMode] = None
    scale_factor: int = 1
    webdriver: Optional[str] = None
    embed_options: Optional[EmbedOptions] = None

# Server options
class ServerOptions:
    port: int = 8888
    open: bool = True
    ip: str = '127.0.0.1'
    n_retries: int = 50
    inline: bool = False

Install with Tessl CLI

npx tessl i tessl/pypi-altair

docs

chart-composition.md

chart-creation.md

configuration-theming.md

data-handling.md

encodings-channels.md

expressions-conditions.md

index.md

parameters-interactions.md

rendering-output.md

transformations.md

tile.json