Embedding vega-lite charts in Hugo
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:
- 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 addingvega: true
to the pre-amble of your post.
|
|
And then in ./layouts/partials/vega.html
.
|
|
- Set up the shortcode in
./layouts/partials/vega.html
. This makes thevegaembed
available.
|
|
- In a hugo post (e.g.
./content/posts/vega.md
), enable the vega libraries withvega: true
in the pre-amble. You can use the shortcode{{< vegaembed id="" spec="" >}}
. Spec is the url to the data in json format.
|
|
The chart below is rendered using the code above:
🚀