Skip to content

Working with Altair#

Open in Colab

Altair is a declarative statistical visualization library for Python.

You can log and display Altair charts as interactive HTML in the Neptune app.

Altair chart in Neptune

See in Neptune  Example script 

Before you start#

Tip

To follow the guide without any setup, run the Colab example.

Altair logging example#

  1. Import Neptune and start a run:

    import neptune.new as neptune
    
    run = neptune.init_run()  # (1)
    
    1. If you haven't set up your credentials, you can log anonymously: neptune.init_run(api_token=neptune.ANONYMOUS_API_TOKEN, project="common/altair-support")
  2. Install vega-datasets to access sample data:

    pip install vega_datasets==0.9.0
    
    conda install -c conda-forge vega_datasets=0.9.0
    
  3. Create a sample figure using data from vega_datasets.data.cars():

    import altair as alt
    from vega_datasets import data
    
    source = data.cars()
    
    brush = alt.selection(type="interval")
    
    points = (
        alt.Chart(source)
        .mark_point()
        .encode(
            x="Horsepower:Q",
            y="Miles_per_Gallon:Q",
            color=alt.condition(brush, "Origin:N", alt.value("lightgray")),
        )
        .add_selection(brush)
    )
    
    bars = (
        alt.Chart(source)
        .mark_bar()
        .encode(y="Origin:N", color="Origin:N", x="count(Origin):Q")
        .transform_filter(brush)
    )
    
    chart = points & bars
    
  4. Upload the chart:

    run["interactive_img"].upload(chart)
    
  5. To stop the connection to Neptune and sync all data, call the stop() method:

    run.stop()
    
    Caution

    Always call stop() in interactive environments, such as a Python interpreter or Jupyter notebook. The connection to Neptune is not stopped when the cell has finished executing, but rather when the entire notebook stops.

    If you're running a script, the connection is stopped automatically when the script finishes executing. However, it's a best practice to call stop() when the connection is no longer needed.

  6. Run your script as you normally would.

    To open the run, click the Neptune link that appears in the console output.

    Example link: https://app.neptune.ai/common/altair-support/e/AL-1

  7. Find the logged images in the All Metadata section:

Back to top