Skip to main content
  1. Posts/

Embedding vega-lite charts in Hugo

·342 words·2 mins

Altair is one of my favourite libraries for data vizualization in Python.

Altair is a declarative statistical visualization library. It is based around the grammar of graphics, which means that you tell it what your data look like and its relations, and the library figures out the rest. This makes it completely different approach for generating graphics than what I’m used to with matplotlib.

It is based on Vega and Vega-Lite, which means altair can render to html or json, which makes it great for showing data in an interactive web environment.

Vega-Embed is a javascript library to make it easy to embed interactive Vega-lite views into web pages. Naturally, I was curious if such plots could be embedded in Hugo blogs using shortcodes.

This is how I got this to work:

  1. Load the required javascript libraries by adding a few lines to the page header. I think the exact filename depends on the theme 1. This worked for me – I added the following code to ./layouts/partials/extend_head.html. The libraries can be enabled by adding vega: true to the pre-amble of your post.
1
2
3
{{ if or .Params.vega .Site.Params.vega }}
	{{ partial "vega.html" . }}
{{ end }}

And then in ./layouts/partials/vega.html.

1
2
3
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm//vega@5"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm//vega-lite@4.17.0"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm//vega-embed@6"></script>
  1. Set up the shortcode in ./layouts/partials/vega.html. This makes the vegaembed available.
1
2
3
4
5
6
<div id='{{ .Get "id" }}'></div>
<script type="text/javascript">
  var spec = '{{ .Get "spec" }}';
  vegaEmbed('#{{ .Get "id" }}', spec).then(function(result) {
  }).catch(console.error);
</script>
  1. In a hugo post (e.g. ./content/posts/vega.md), enable the vega libraries with vega: true in the pre-amble. You can use the shortcode {{< vegaembed id="" spec="" >}}. Spec is the url to the data in json format.
1
2
3
4
5
6
---
title: "Vega embed example"
vega: true
---

{{< vegaembed id="vis" spec="https://raw.githubusercontent.com/vega/vega/master/docs/examples/bar-chart.vg.json" >}}

The chart below is rendered using the code above:

🚀


  1. Update 2022-12-30: It turns out that the name of extend_head is indeed theme specific. For congo the file must be named extend-head.html↩︎