A demo of Vega-Lite with websockets. Uses Vega-Embed to access the Vega View API.
In this demo, we don't use an external data source and instead send and receive data from an echo server. Of course you would never do this in practice but this way we can have both the sender and the receiver in the same piece of code to illustrate the appraoch.
The demo sends a row every second until all data has been transmitted. To restart the demo, refresh the page.
xxxxxxxxxx
<head>
<meta charset="utf-8">
<script src="https://cdn.jsdelivr.net/npm/vega@3"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-lite@2"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-embed@3"></script>
</head>
<body>
<div id="vis"></div>
<script>
const data = [
{"a": "A","b": 28}, {"a": "B","b": 55}, {"a": "C","b": 43},
{"a": "D","b": 91}, {"a": "E","b": 81}, {"a": "F","b": 53},
{"a": "G","b": 19}, {"a": "H","b": 87}, {"a": "I","b": 52}
];
const spec = "bar.vl.json";
vegaEmbed('#vis', spec, {defaultStyle: true})
.then(function(result) {
const view = result.view;
// connect to simple echo server
const conn = new WebSocket("wss://echo.websocket.org");
conn.onopen = function(event) {
// insert data as it arrives from the socket
conn.onmessage = function(event) {
console.log(event.data);
// Use the Vega view api to insert data
view.insert("table", JSON.parse(event.data)).run();
}
// send some data into the echo socket every second
const interval = window.setInterval(function() {
if (data.length) {
conn.send(JSON.stringify(data.pop()));
} else {
clearInterval(interval);
}
}, 1000);
}
})
.catch(console.warn);
</script>
</body>
https://cdn.jsdelivr.net/npm/vega@3
https://cdn.jsdelivr.net/npm/vega-lite@2
https://cdn.jsdelivr.net/npm/vega-embed@3