Vega Embed on Jekyll
Installing and using Vega Embed with my Jekyll Blog
If I want to blog about Vega I want to be able to render the visuals on the post for full interactivity rather than use static images. In that vein I enabled Vega-Embed for the blog. Vega-Embed automatically renders img from the given spec, and adds the ability to export the graph as a image, view the source/compiled spec, or open the spec in Vega Editor. Lets have a look at how to enable and use it.
Load The Vega Libraries
Add the following to head.html
.
<script src="https://cdn.jsdelivr.net/npm/vega@5"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-lite@5"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-embed@6"></script>
Render Vega on Post
Add a script that calls the vegaEmbed()
function in the post.
Embedded data and spec
<div id="vis"></div>
<script type="text/javascript">
var spec = {
$schema: 'https://vega.github.io/schema/vega-lite/v5.json',
description: 'A simple bar chart with embedded data.',
width: 400,
height: 200,
data: {
values: [
{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}
]
},
mark: 'bar',
encoding: {
x: {field: 'a', type: 'ordinal'},
y: {field: 'b', type: 'quantitative'}
}
};
vegaEmbed('#vis', spec);
</script>
Remote Spec
<div id="vis"></div>
<script type="text/javascript">
var spec = "https://raw.githubusercontent.com/vega/vega/master/docs/examples/bar-chart.vg.json";
vegaEmbed('#vis', spec).then(function(result) {}).catch(console.error);
</script>
Interactive Visual
Lets quickly test one of the examples provided by vega with some interactive elements.
Embed Options
You can also specify a number of Options in the vegaEmbed()
function, such as Themes, Vega tooltips, renderer [‘svg’, ‘canvas’], width, height, etc.
Themes
I’ve seen a powerbi
theme so we have to give that a go.
<div id="vis"></div>
<script type="text/javascript">
var spec = "...";
vegaEmbed('#vis', spec, {theme: 'powerbi'}).then(function(result) {}).catch(console.error);
</script>
Testing With Local Spec and Data
Lets now try with a locally saved spec.
<div id="vis5"></div>
<script type="text/javascript">
var spec = "/assets/vega/0017-VegaEmbed/bar.v1.json";
vegaEmbed('#vis5', spec).then(function(result) {}).catch(console.error);
</script>
Conclusion
Vega-Embed is fairly painless to setup and a great resource. Will try to put out some Vega posts in the near future.