Skip to content

Instantly share code, notes, and snippets.

@Hugovdberg
Created August 3, 2018 12:58
Show Gist options
  • Save Hugovdberg/96f0645ad13717d282026222eb5c32bf to your computer and use it in GitHub Desktop.
Save Hugovdberg/96f0645ad13717d282026222eb5c32bf to your computer and use it in GitHub Desktop.
nbconvert template with support for (interactive) altair plots
{% extends 'full.tpl' %}
{% 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 %}
<div id="vis{{cell['execution_count']}}"></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']}}", spec, opt);
</script>
{% else %}
{{super()}}
{% endif %}
{%- endblock data_priority -%}
@knanne
Copy link

knanne commented Mar 11, 2019

Thanks for this. Your gist does not work on all visualization types. Maps created in Altair were not included with 'application/vnd.vegalite.v2+json', because it was a different MIME type. I extended your code to all listed here and it worked.

{% for mimetype in ('application/vnd.vegalite.v1+json','application/vnd.vega.v2+json','application/vnd.vegalite.v2+json','application/vnd.vega.v3+json') %}
  {% if mimetype in output.data %}
    <div id="vis{{cell['execution_count']}}"></div>
    <script type="text/javascript">
      var spec = {{ output.data[mimetype] }};
      var opt = {"renderer": "canvas", "actions": false};
      vegaEmbed("#vis{{cell['execution_count']}}", spec, opt);
    </script>
  {% elif loop.index == 1 %}
    {{super()}}
  {% endif %}
{% endfor %}

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