In [1]:
import random
import time
In [2]:
spec_no_data = {
"$schema": "https://vega.github.io/schema/vega-lite/v4.json",
"mark": "point",
"data": {
"name": "data",
"values": [],
},
"encoding": {
"x": {"type": "quantitative", "field": "x"},
"y": {"type": "quantitative", "field": "y"},
}
}
spec_with_data = spec_no_data.copy()
spec_with_data["data"] = {
"name": "data",
"values": [
{"x": random.gauss(0, 1), "y": random.gauss(0, 1), "t": t}
for t in range(5)
],
}
In [3]:
from vega import VegaLite
VegaLite(spec=spec_with_data)
Out[3]:
In [4]:
from vega.widget import VegaWidget
widget = VegaWidget(spec=spec_no_data)
values = [
dict(
x=random.gauss(0.0, 1.0),
y=random.gauss(0.0, 1.0),
t=0,
)
for _ in range(10)
]
display(widget)
widget.update('data', insert=values)
In [5]:
# The spec can be updated after the widget has been displayed. However, any
# data is inserted via update is lost and needs to be re-inserted.
widget.spec = dict(spec_no_data, mark="line")
widget.update('data', insert=values)
In [6]:
# Similarly the options can be updated after the widget has been displayed.
# Again, any data is inserted via update is lost and needs to be re-inserted.
widget.opt = {"theme": "dark"}
widget.update('data', insert=values)
In [7]:
print("the current spec / options")
print(widget.spec)
print(widget.opt)
The VegaWidget can also be embedded into larger ipywidgets layout and use interactive features, such as buttons or similar interactive elements.
In [8]:
from ipywidgets import VBox, Label, Button
In [9]:
plot = VegaWidget(spec=spec_with_data)
button = Button(description="Add new data point")
t = 5
@button.on_click
def on_click_handler(*_):
global t
value = dict(
x=random.gauss(0.0, 1.0),
y=random.gauss(0.0, 1.0),
t=t,
)
plot.update('data', insert=[value], remove=f'datum.t <= {t - 5}')
t += 1
VBox([Label("Vega plot embedded in another widget"), plot, button])
In [10]:
from vega.widget import VegaWidget
widget = VegaWidget(spec=spec_no_data)
values = [
dict(
x=random.gauss(0.0, 1.0),
y=random.gauss(0.0, 1.0),
t=0,
)
for _ in range(10)
]
display(widget)
widget.update('non_existing', insert=values)
In [ ]: