Dash Vega-Altair Component

I’ve created dash-vega-components which you can use to add interactive Altair charts to your Dash application:

pip install dash-vega-components
import altair as alt
from dash import Dash, Input, Output, callback, dcc, html
from vega_datasets import data

import dash_vega_components as dvc

# Passing a stylesheet is not required
app = Dash(
    __name__, external_stylesheets=["https://codepen.io/chriddyp/pen/bWLwgP.css"]
)

app.layout = html.Div(
    [
        html.H1("Altair Chart"),
        dcc.Dropdown(["All", "USA", "Europe", "Japan"], "All", id="origin-dropdown"),
        # Optionally, you can pass options to the Vega component.
        # See https://github.com/vega/vega-embed#options for more details.
        dvc.Vega(id="altair-chart", opt={"renderer": "svg", "actions": False}),
    ]
)


@callback(Output("altair-chart", "spec"), Input("origin-dropdown", "value"))
def display_altair_chart(origin):
    source = data.cars()

    if origin != "All":
        source = source[source["Origin"] == origin]

    chart = (
        alt.Chart(source)
        .mark_circle(size=60)
        .encode(
            x="Horsepower",
            y="Miles_per_Gallon",
            color=alt.Color("Origin").scale(domain=["Europe", "Japan", "USA"]),
            tooltip=["Name", "Origin", "Horsepower", "Miles_per_Gallon"],
        )
        .interactive()
    )
    return chart.to_dict()


if __name__ == "__main__":
    app.run(debug=True)

dvc_example

Feedback is very welcome!

5 Likes

Congratulations and thanks for sharing, @binste . Altair is very popular in the Python community, so I’m sure the community would really benefit from having this additional capability to integrate their charts into Dash.

Are there any limitations or we can add any altair chart we want?

Thanks @adamschroeder! Any Altair chart should work including all the interactivity features as well as multi-view charts. If someone encounters an issue, please let me know on GitHub or here and I’m happy to have a look.

2 Likes

Just wanted to add that dash-vega-components is now an official Vega-Altair project. With this, we’d like to show our dedication to make Altair a first-class visualization library for Dash.

3 Likes

I am replying just to show some support to the project, it makes interactive plots coding even easier!! Keep it going :hand_with_index_finger_and_thumb_crossed:

1 Like