Skip to content

Instantly share code, notes, and snippets.

@domoritz
Last active January 8, 2020 16:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save domoritz/8e1e4da185e1a32c7e54934732a8d3d5 to your computer and use it in GitHub Desktop.
Save domoritz/8e1e4da185e1a32c7e54934732a8d3d5 to your computer and use it in GitHub Desktop.
Vega-Lite with Websockets
license: bsd-3-clause

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.

{
"$schema": "https://vega.github.io/schema/vega-lite/v2.json",
"description": "A simple bar chart with embedded data.",
"width": 360,
"data": {
"name": "table"
},
"mark": "bar",
"encoding": {
"x": {"field": "a", "type": "ordinal"},
"y": {"field": "b", "type": "quantitative"},
"tooltip": {"field": "b", "type": "quantitative"}
}
}
<!DOCTYPE html>
<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>
@pohlt
Copy link

pohlt commented Sep 27, 2018

This did not work for me: If the websocket connects before the onopen event is set, all the stuff in conn.onopen will never be called.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment