Embedding vega-lite charts in Zola

2022-11-20

Updated 2026-11-26: Updated blog snippets to work with Zola instead of 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 Zola blogs using components.

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. This worked for me -- I added the following code to ./templates/base.html. The libraries can be enabled by adding vega = true to the [extra] section of the pre-amble of your post.
{% set vega_scripts = page is defined and page.extra is defined and page.extra.vega | default(value=false) %}
{% if vega_scripts %}
<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>
{% endif %}
  1. Set up the component in ./templates/components/vega.html. This makes the vega component available.
{% component vega(id, spec) %}
<div id="{{ id }}"></div>
<script type="text/javascript">
  window.addEventListener("DOMContentLoaded", function () {
    vegaEmbed(document.getElementById({{ id | json_encode | safe }}), {{ spec | json_encode | safe }}).then(function(result) {
    }).catch(console.error);
  });
</script>
{% endcomponent vega %}

Note that this uses the component syntax introduced in Zola 0.23

  1. In a zola post (e.g. ./content/posts/vega.md), enable the vega libraries with vega = true in the pre-amble. You can use the component shown below. Spec is the url to the data in json format.
+++
title = "Vega embed example"

[extra]
vega = true
+++

{{<vega 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: