How to add/ modify/ patch altair chart data dynamically?

Question:

I would like to add chart(s), or data to existing chart dynamically (via ipywidget.interact) as in the code below (chart + dotchart). I get nearly what I want except whole chart gets re-drawn and this causes flickering.

How do I add/ modify/ patch data dynamically and avoid re-drawing whole chart?

Thanks!

import pandas as pd
import numpy as np
import altair as alt
from ipywidgets import interact

df = pd.DataFrame({"xval": range(100), "yval": np.random.randint(0,100,100)})
chart = alt.Chart(df).mark_point().encode(x="xval", y="yval",)

def update(x, y):
    dot = pd.DataFrame(dict(x=[x], y=[y]))
    dotchart = alt.Chart(dot).mark_point().encode(x="x", y="y", color=alt.value("red"))
    return chart + dotchart 

interact(update, x=(0, 100), y=(0, 100))
# x, y widgets that control position of 'red dot'
Asked By: k1m190r

||

Answers:

The only way to patch data into an Altair chart without re-rendering it is in Javascript, using the Vega View API. You can see an example of this here: https://vega.github.io/vega-lite/tutorials/streaming.html.

I don’t know of any prior work on calling the Vega view API from Python, but it’s possible in principle.

See the related Altair feature request here: https://github.com/altair-viz/altair/issues/426.

Answered By: jakevdp

you may be able to do so using the top-level chart configuration methods that altair provides. See here: https://altair-viz.github.io/user_guide/configuration.html

This way you can update many many properties of the current chart without regenerating it.

Answered By: Reza Partovi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.