A Jinja Altair/Vega Shortcode

The Shortcode Template

This is a shortcode-template to add the HTML for an altair-vega sketch (both the script and div tags). The shortcode takes two arguments:

  • source: the name of the javascript chart file
  • divid: the ID of the div in the HTML where the chart will go.

The file is in shortcodes/altairdiv.tmpl. Note that since it's a template it will only work with Jinja. To make it work with mako you need another template (which I haven't made yet).

<div class="altair-vega" id="{{ divid }}"></div>

<script src="{{ source }}"></script>

Note: The only thing that makes this altair-specific is the class. This is also the case with the P5 Div Shortcode, so perhaps a generic shortcode that takes the class as a third-argument would be better… Although then you'd have to remember the class names.

Try it Out

As noted, this is a Jinja shortcode so the conf.py has to be pointing to the jinja theme.

 # from pypi
 import altair
 import pandas

 # monkey
 from graeae.visualization.altair_helpers import output_path, save_vega_embed
OUTPUT = output_path(slug="a-jinja-altairvega-shortcode")

data = pandas.DataFrame(dict(a=[1, 3, 5], b=[3, 9, 27]))
chart = altair.Chart(data).mark_bar().encode(
    x="a",
    y="b"
).properties(height=600, width="container")

save_vega_embed(chart, name="shortcode-bar",output_path=OUTPUT, div_id="shortcode-bar-id")