Vega-Altair Documentation

repository·main·Indexed 27 days ago

https://github.com/vega/altair

A declarative statistical visualization library for Python built on top of the Vega-Lite JSON specification. It enables the creation of complex, interactive visualizations and linked dashboards using a declarative grammar. Features include Jupyter integration via JupyterChart and %%vegalite magic commands, a theme registration system, and utilities for exporting charts to JSON, CSV, or values.

Tokens
75.3K
Snippets
239
Records
354
Agent score
92%

What's inside Vega-Altair

  1. Overview of Altair

    main

    Altair is a declarative statistical visualization library for Python. It is designed for scientists and data scientists performing exploratory data analysis.

    Key characteristics:

    • Declarative API: Visualizations are specified by describing how data is mapped to visual properties (position, color, size, etc.) rather than by manual drawing commands.
    • Vega-Lite Based: Altair is built on top of the Vega-Lite visualization grammar, providing a wide range of statistical visualizations through a small set of grammar primitives.
    • Interactivity: Supports complex interactions (like interval selections and multi-selections) that can drive filters and transformations across multiple plots.
    • Rendering: The Python API emits Vega-Lite JSON data, which is rendered in environments like Jupyter Notebook, JupyterLab, or nteract using the Vega-Lite JavaScript library.
  2. Overview of Vega-Altair

    main
    Vega-Altair is a declarative visualization library for Python. It provides a simple, friendly, and consistent API built on top of the Vega-Lite grammar, designed to facilitate data exploration with minimal code.
  3. Understand the Vega-Altair design approach

    main

    Vega-Altair is designed to simplify exploratory data visualization by providing a constrained, declarative Python API. Instead of being a standalone rendering engine, it follows a layered design pattern:

    1. Declarative API: You use the Vega-Altair Python API to describe what you want to see, rather than how to draw it.
    2. JSON Specification: The API emits JSON output that adheres to the Vega-Lite specification.
    3. Rendering: The resulting Vega-Lite specification is rendered using existing visualization libraries (like Vega).

    This approach allows users to start with simple, high-level commands for statistical visualization and transition to advanced customization by leveraging the underlying renderer's capabilities.

  4. Understand Altair Data Transformers

    main

    Altair's data transformation API manages how pandas DataFrames are sanitized and serialized before being passed to a Vega-Lite or Vega renderer. This includes tasks like converting DataFrames to JSON, sampling rows, or limiting the number of rows for performance.

    Note: The Altair data transformation API is distinct from the transform API within Vega and Vega-Lite.

  5. Explore the Altair ecosystem and related projects

    main

    Altair integrates with or is extended by several specialized projects:

    Core & Conversion

    • Vega-Lite: The higher-level visualization grammar that Altair implements.
    • vl-convert: A Python library for converting Altair/Vega-Lite specifications into static images (SVG/PNG) or Vega specifications without external dependencies.

    Performance & Backend

    • VegaFusion: Provides server-side scaling to accelerate interactive charts, perform data-intensive aggregations, and prune unused columns.
    • altair_pandas: An Altair backend for the pandas plotting API.

    Specialized Plotting & Extensions

    • altair_recipes: A collection of ready-made statistical graphics.
    • nx_altair: A library for drawing NetworkX graphs as Altair Charts.
    • Altair Ally: A companion package providing shortcuts for exploratory data analysis (EDA) and visualizing entire DataFrames.
    • gif: An extension for creating Altair and matplotlib animations using a decorator interface.
    • Altair-upset: Creates interactive UpSet plots (alternatives to Venn diagrams) supporting Pandas and Polars.

    Other Interfaces

    • Altair in R: An R interface to the Altair Python package.
  6. Integrate Altair with Dashboards

    main

    Altair is compatible with several Python dashboarding packages. Some packages support reading out parameters from the chart, allowing for interactive dashboards where selections update other components (like tables).

    PackageDisplays Interactive ChartsSupports Reading Parameters
    Panel
    Plotly Dash
    Jupyter Voila (via JupyterChart)
    Marimo
    Shiny (via JupyterChart)
    Solara
    Streamlit

    For use cases where full server-side interactivity isn't required, tools like Quarto or Jupyter Book can generate HTML pages containing Altair charts without needing a web server.

  7. Understand the core concepts of Altair interaction

    main

    Altair uses a declarative grammar for interaction based on three core concepts:

    1. Parameters: The basic building blocks. These can be simple variables or complex selections that map user input (like mouse clicks or drags) to data queries.
    2. Conditions and Filters: These respond to changes in parameter values to update chart elements dynamically.
    3. Widgets and Bindings: Chart input elements (like drop-down menus, radio buttons, or sliders) can be bound to parameters to allow users to manipulate charts.

    Additionally, you can use Expressions for custom calculations via formulas and JupyterCharts to access parameter values directly from Python.

  8. Map encodings to constant visual values using `alt.value`

    main

    Use alt.value to map an encoding channel to an absolute visual constant, such as a specific pixel position, an RGB color name, or a shape name. Unlike alt.datum, alt.value ignores the data scale and uses absolute units (e.g., alt.value(300) positions an element 300 pixels from the chart border).

    import altair as alt
    from altair.datasets import data
    
    source = data.stocks()
    base = alt.Chart(source)
    lines = base.mark_line().encode(
        x="date:T",
        y="price:Q",
        color="symbol:N"
    )
    # Position the rule 300 pixels from the top border
    rule = base.mark_rule(strokeDash=[2, 2]).encode(
        y=alt.value(300)
    )
    
    lines + rule
  9. Pass data via URL to reduce notebook size

    main

    Instead of embedding data directly, you can store it in a separate file and pass the URL to the chart. This improves notebook performance and interactivity.

    Local Filesystem: You can save data to a JSON file and pass the path to alt.Chart().

    url = 'data.json'
    data.to_json(url, orient='records')
    chart = alt.Chart(url).mark_line().encode(x='x:Q', y='y:Q')

    Automatic JSON/CSV Transformers: Altair provides transformers that handle this process transparently:

    alt.data_transformers.enable('json')
    # Note: 'csv' is also available but does not preserve data types as well as JSON

    Vega Datasets: For built-in Vega datasets, use the url attribute:

    from altair.datasets import data
    source = data.cars.url
    alt.Chart(source).mark_point()
  10. Bind a widget to an encoding channel using parameters

    main

    Altair does not support direct binding of a selection to an encoding channel (e.g., bind='x'). To update which column is displayed on an axis based on a widget selection, you must:

    1. Create a binding (e.g., alt.binding_select).
    2. Create a parameter (alt.param) that uses that binding.
    3. Use transform_calculate to dynamically compute the encoding value by referencing the parameter name within a datum[] lookup.
    4. Add the parameter to the chart using .add_params().
    dropdown = alt.binding_select(
        options=['Horsepower', 'Displacement', 'Weight_in_lbs', 'Acceleration'],
        name='X-axis column '
    )
    xcol_param = alt.param(
        value='Horsepower',
        bind=dropdown
    )
    
    alt.Chart(data.cars.url).mark_circle().encode(
        x=alt.X('x:Q').title(''),
        y='Miles_per_Gallon:Q',
        color='Origin:N'
    ).transform_calculate(
        x=f'datum[{xcol_param.name}]'
    ).add_params(
        xcol_param
    )
  11. Use expressions in chart titles

    main

    You can use alt.expr() to create dynamic chart titles that update based on parameter values.

    Important Notes:

    • When using JavaScript-style strings in an f-string for a title, use nested quotations (e.g., f'"Text " + {param.name}') so the parameter value is correctly interpreted as part of the string.
    • To reference a field from a selection parameter in a title, use the syntax {selection.name}.{field_name} (e.g., {selection.name}.Origin).
    • Currently, expressions are supported in alt.Title, but not yet in subtitles or guide titles (axis and legends).
    from altair.datasets import data
    
    cars = data.cars.url
    input_dropdown = alt.binding_select(options=['Europe', 'Japan', 'USA'], name='Region ')
    selection = alt.selection_point(fields=['Origin'], bind=input_dropdown, value='Europe')
    
    # Accessing a selection field in the title
    title = alt.Title(alt.expr(f'"Cars from " + {selection.name}.Origin'))
    
    alt.Chart(cars, title=title).mark_point().encode(
        x='Horsepower:Q',
        y='Miles_per_Gallon:Q',
    ).add_params(
        selection
    ).transform_filter(
        selection
    )