Skip to content

Instantly share code, notes, and snippets.

@Hugovdberg
Last active March 16, 2019 12:04
Show Gist options
  • Select an option

  • Save Hugovdberg/66da814c3de08e8578465991ee78171c to your computer and use it in GitHub Desktop.

Select an option

Save Hugovdberg/66da814c3de08e8578465991ee78171c to your computer and use it in GitHub Desktop.
nbconvert template for altair/vegalite output to html, with a hacky way to ensure unique visualisation numbers
{% extends 'full.tpl' %}
{% set altair = {'vis_number': 0} %}
{% block header %}
<script src="https://cdn.jsdelivr.net/npm/vega@3"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-lite@2"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-embed@3"></script>
{{super()}}
{% endblock header %}
{%- block data_priority scoped -%}
{% if 'application/vnd.vegalite.v2+json' in output.data %}
{% if altair.update({'vis_number': altair.vis_number+1}) %}{% endif %}
<div id="vis{{cell['execution_count']}}_{{ altair.vis_number }}"></div>
<script type="text/javascript">
var spec = {{ output.data['application/vnd.vegalite.v2+json'] }};
var opt = {"renderer": "canvas", "actions": false};
vegaEmbed("#vis{{cell['execution_count']}}_{{ altair.vis_number }}", spec, opt);
</script>
{% else %}
{{super()}}
{% endif %}
{%- endblock data_priority -%}
@knanne
Copy link

knanne commented Mar 16, 2019

I have implemented your gist as and extension to my own template. It works for faceted visualizations with multiple charts, but not two charts put together.

Please see live example here https://knanne.github.io/notebooks/visualize_strava_data_in_python.html#Plots (both scatterplots in facet are interactive while only the right bar chart in combined plot is...any idea on the fix? Thanks a lot! - Kain

FIXED: needed to exclude the "image/png" key in cell output after writing vega spec with {% block data_png scoped %}{% endblock data_png %}. Working solution at https://gist.github.com/knanne/37712efaea0be6f10eb027c7aa82801e

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment