Skip to content

Instantly share code, notes, and snippets.

@erisonliang
Forked from john-guerra/.block
Created October 11, 2022 14:48
Show Gist options
  • Select an option

  • Save erisonliang/28f2495d6147f387ee099497fe55fbd4 to your computer and use it in GitHub Desktop.

Select an option

Save erisonliang/28f2495d6147f387ee099497fe55fbd4 to your computer and use it in GitHub Desktop.
Vega-lite: load data dynamically on run-time with vegaEmbed
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

forked from john-guerra's block: Vega-lite: load data dynamically on run-time

<!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 src="https://cdn.jsdelivr.net/npm//vega-embed@3.11"></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}
];
const embed_opt = {"mode": "vega-lite"};
const el = document.getElementById('vis');
const view = vegaEmbed("#vis", spec, embed_opt)
.catch(error => showError(el, error))
.then((res) => res.view.insert("myData", myData).run());
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment