or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

chart-composition.mdchart-creation.mdconfiguration-theming.mddata-handling.mdencodings-channels.mdexpressions-conditions.mdindex.mdparameters-interactions.mdrendering-output.mdtransformations.md
tile.json

tessl/pypi-altair

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

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/altair@5.5.x

To install, run

npx @tessl/cli install tessl/pypi-altair@5.5.0

index.mddocs/

Altair

A declarative statistical visualization library for Python that provides a simple, friendly, and consistent API built on top of the Vega-Lite JSON specification. Altair enables developers to create beautiful and effective visualizations with minimal code by focusing on describing what they want rather than how to draw it.

Package Information

  • Package Name: altair
  • Language: Python
  • Installation: pip install altair
  • Optional Dependencies: pip install altair[all] for full functionality

Core Imports

import altair as alt

For specific components:

from altair import Chart, param, expr, datum

Basic Usage

import altair as alt
import pandas as pd

# Enable Altair in Jupyter notebooks
alt.data_transformers.enable('json')

# Create sample data
data = pd.DataFrame({
    'x': [1, 2, 3, 4, 5],
    'y': [2, 5, 3, 8, 7],
    'category': ['A', 'B', 'A', 'B', 'A']
})

# Create a simple scatter plot
chart = alt.Chart(data).mark_circle(size=100).encode(
    x='x:Q',
    y='y:Q',
    color='category:N'
).properties(
    title='Simple Scatter Plot'
)

chart.show()

# Create a bar chart with aggregation
bar_chart = alt.Chart(data).mark_bar().encode(
    x='category:N',
    y='mean(y):Q',
    color='category:N'
).properties(
    title='Average Y by Category'
)

bar_chart.show()

Architecture

Altair follows a grammar of graphics approach where visualizations are constructed by combining data, marks, encodings, and transformations:

  • Chart: The primary object that combines data with visual specifications
  • Marks: Visual elements (point, line, bar, area, etc.) that represent data
  • Encodings: Mappings from data fields to visual properties (position, color, size, etc.)
  • Transformations: Data processing operations (filter, aggregate, calculate, etc.)
  • Parameters: Interactive elements for dynamic visualizations
  • Expressions: Calculated fields and conditional logic using Vega expressions

This declarative approach allows complex visualizations to be built compositionally, with clear separation between data preparation, visual encoding, and interactivity.

Capabilities

Chart Creation

Core functionality for creating and configuring charts with data, marks, and encodings. The Chart class is the primary interface for building visualizations.

class Chart:
    def __init__(self, data=None, **kwargs): ...
    def mark_point(self, **kwargs): ...
    def mark_line(self, **kwargs): ...
    def mark_bar(self, **kwargs): ...
    def mark_area(self, **kwargs): ...
    def encode(self, **kwargs): ...
    def transform_filter(self, predicate): ...
    def properties(self, **kwargs): ...

Chart Creation

Data Handling

Data transformation, loading, and preprocessing functionality including support for pandas DataFrames, CSV/JSON files, and various data formats.

def to_json(data, **kwargs): ...
def to_csv(data, **kwargs): ...
def limit_rows(max_rows=5000): ...
def sample(n=None, frac=None): ...

# Data transformers registry
data_transformers = PluginRegistry()

Data Handling

Encodings & Channels

Visual encoding channels that map data fields to visual properties like position, color, size, and shape. These form the core of the grammar of graphics implementation.

class X:
    def __init__(self, field=None, type=None, **kwargs): ...

class Y:
    def __init__(self, field=None, type=None, **kwargs): ...

class Color:
    def __init__(self, field=None, type=None, **kwargs): ...

class Size:
    def __init__(self, field=None, type=None, **kwargs): ...

Encodings & Channels

Transformations

Data transformation operations that can be applied to datasets within chart specifications, including filtering, aggregation, binning, and calculations.

# Available as Chart methods
def transform_filter(self, predicate): ...
def transform_aggregate(self, **kwargs): ...
def transform_calculate(self, **kwargs): ...
def transform_bin(self, **kwargs): ...
def transform_lookup(self, **kwargs): ...

Transformations

Parameters & Interactions

Interactive parameters and selections that enable dynamic, interactive visualizations with user input controls and cross-filtering.

def param(name=None, value=None, bind=None, **kwargs): ...

class Parameter:
    def __init__(self, **kwargs): ...

def selection_point(**kwargs): ...
def selection_interval(**kwargs): ...

Parameters & Interactions

Expressions & Conditions

Expression system for calculated fields, conditional logic, and dynamic values using Vega expression language with mathematical, string, and logical operations.

class ExpressionAPI:
    # Mathematical functions
    def abs(self, expr): ...
    def sin(self, expr): ...
    def log(self, expr): ...
    
    # String functions  
    def upper(self, expr): ...
    def length(self, expr): ...
    
    # Conditional functions
    def if_(self, test, then, else_): ...

expr = ExpressionAPI()
datum = DatumExpression()

Expressions & Conditions

Chart Composition

Functions for combining multiple charts through layering, concatenation, faceting, and repetition to create complex multi-view visualizations.

def layer(*charts, **kwargs): ...
def hconcat(*charts, **kwargs): ...
def vconcat(*charts, **kwargs): ...
def concat(*charts, **kwargs): ...
def repeat(**kwargs): ...

Chart Composition

Configuration & Theming

Theme system and configuration options for customizing chart appearance, including axis styling, color schemes, and layout properties.

# Theme registry
theme = ThemeRegistry()

class Config:
    def __init__(self, **kwargs): ...

class AxisConfig:
    def __init__(self, **kwargs): ...

class LegendConfig:
    def __init__(self, **kwargs): ...

Configuration & Theming

Rendering & Output

Display and output options for charts including Jupyter notebook integration, static image export, and HTML generation.

# Renderer registry
renderers = PluginRegistry()

class Chart:
    def show(self): ...
    def save(self, filename, **kwargs): ...
    def to_dict(self): ...
    def to_json(self): ...

Rendering & Output

Utility Functions

Utility functions and constants for working with Altair specifications and handling common tasks.

def parse_shorthand(shorthand, data=None):
    """
    Parse encoding shorthand string into field name, data type, and aggregate.
    
    Parameters:
    - shorthand: Shorthand string (e.g., 'field:Q', 'mean(field):Q')
    - data: Optional data for field validation
    
    Returns:
    dict: Parsed components
    """

class Undefined:
    """Sentinel object representing undefined/unspecified values."""

# Exception classes
class AltairDeprecationWarning(UserWarning):
    """Warning for deprecated Altair functionality."""

class MaxRowsError(Exception):
    """Exception raised when data exceeds maximum allowed rows."""

# Version constants
VEGALITE_VERSION: str  # Vega-Lite specification version
VEGA_VERSION: str      # Vega version
VEGAEMBED_VERSION: str # Vega-Embed version
SCHEMA_VERSION: str    # Schema version
SCHEMA_URL: str        # Schema URL

Common Types

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

# Data types
ChartDataType = Union[pd.DataFrame, str, dict, list]
FieldName = str
DataType = Union['quantitative', 'ordinal', 'nominal', 'temporal']

# Basic chart configuration
class ChartConfig:
    width: Optional[int] = None
    height: Optional[int] = None
    title: Optional[str] = None
    background: Optional[str] = None

# Encoding types
EncodingType = Union[str, Dict[str, Any]]
ScaleType = Union['linear', 'log', 'sqrt', 'symlog', 'time', 'utc', 'ordinal', 'point', 'band']