Skip to content

Instantly share code, notes, and snippets.

@john-guerra
Last active February 23, 2021 07:40
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save john-guerra/3d4325d774ab3cac4e0ed0156ce469d2 to your computer and use it in GitHub Desktop.
Save john-guerra/3d4325d774ab3cac4e0ed0156ce469d2 to your computer and use it in GitHub Desktop.
Vega-lite: load data dynamically on run-time
license: mit

The vega-lite and vega documentations barely mention how to load data dynamically at run time. However, I couldn't find an example on how to make it work. It seems like you cannot use vegaEmbed for that, and you must use vega viewer. However for this to work you need to compile your spec first to vega.

Built with blockbuilder.org

<!DOCTYPE html>
<head>
<meta charset="utf-8">
</head>
<div id="vis"></div>
<body>
<script src="https://cdn.jsdelivr.net/npm//vega@3.3.1"></script>
<script src="https://cdn.jsdelivr.net/npm//vega-lite@2.4.3"></script>
<script>
var spec = {
"$schema": "https://vega.github.io/schema/vega-lite/v2.json",
"description": "A simple bar chart with embedded data.",
"data": {
"name": "myData"
},
"mark": "bar",
"encoding": {
"y": {"field": "a", "type": "ordinal"},
"x": {"field": "b", "type": "quantitative"}
}
}
var myData = [
{"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}
];
renderVegaLite(spec, myData);
function renderVegaLite(spec, data) {
// First compile vega-lite to vega
var vgSpec = vl.compile(spec).spec;
view = new vega.View(vega.parse(vgSpec))
.logLevel(vega.Warn)
.renderer("canvas") // set renderer (canvas or svg)
.initialize(document.querySelector("#vis")) // initialize view within parent DOM container
.insert("myData", data) // Insert the named data source
.hover() // enable hover encode set processing
.run();
}
</script>
</body>
@Recodify
Copy link

Recodify commented Dec 3, 2018

Thanks very much for this. I was struggling to get it to work using vegaEmbed but this has solved it for me. It almost works with vegaEmbed but the chart would only render when I moused-over the chart and also when the data set was changed it seem to fail to clear previous marks.

How did you figure this out, I'm also struggling to find mention of this in the docs. Vega-lite is so close to being the perfect charting solution but it seems there are some really common use cases that is struggles with!

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