Skip to content

Instantly share code, notes, and snippets.

@knanne
Last active September 5, 2019 07:58
Show Gist options
  • Save knanne/37712efaea0be6f10eb027c7aa82801e to your computer and use it in GitHub Desktop.
Save knanne/37712efaea0be6f10eb027c7aa82801e to your computer and use it in GitHub Desktop.
nbconvert template extension for ipynb to html with working altair interactive charts
{% extends "full.tpl" %}
{% set altair = {'vis_number': 1} %}
{% block header %}
<script src="https://cdn.jsdelivr.net/npm/vega@3"></script>
<script src="https://cdn.jsdelivr.net/npm/vega@5"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-lite@2"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-lite@3"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-embed@3"></script>
{{super()}}
{% endblock header %}
{% block data_png scoped %}
{% if 'application/vnd.vegalite.v1+json' in output.data %}
{% elif 'application/vnd.vegalite.v2+json' in output.data %}
{% elif 'application/vnd.vegalite.v3+json' in output.data %}
{% elif 'application/vnd.vega.v2+json' in output.data %}
{% elif 'application/vnd.vega.v3+json' in output.data %}
{% else %}
{{super()}}
{% endif %}
{% endblock data_png %}
{% block data_text scoped %}
{% if 'application/vnd.vegalite.v1+json' in output.data %}
{% elif 'application/vnd.vegalite.v2+json' in output.data %}
{% elif 'application/vnd.vegalite.v3+json' in output.data %}
{% elif 'application/vnd.vega.v2+json' in output.data %}
{% elif 'application/vnd.vega.v3+json' in output.data %}
{% else %}
{{super()}}
{% endif %}
{% endblock data_text %}
{% block data_priority scoped %}
{% for mimetype in (
'application/vnd.vegalite.v1+json',
'application/vnd.vegalite.v2+json',
'application/vnd.vegalite.v3+json',
'application/vnd.vega.v2+json',
'application/vnd.vega.v3+json')
%}
{% if mimetype 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[mimetype] | replace("None","null") | replace("True","true") | replace("False","false") }};
var opt = {"renderer": "canvas", "actions": false};
vegaEmbed("#vis{{cell['execution_count']}}_{{ altair.vis_number }}", spec, opt);
</script>
{% elif loop.index == 1 %}
{{super()}}
{% endif %}
{% endfor %}
{% endblock data_priority %}
@knanne
Copy link
Author

knanne commented Mar 16, 2019

Working solution for issue described in vega/altair#329
Credit to @Hugovdberg for the base implementation here

Use:

  1. download this template
  2. run jupyter nbconvert --to html --template nbconvert_template_altair.tpl <YOUR_NOTEBOOK.ipynb>

@knanne
Copy link
Author

knanne commented Mar 16, 2019

@knanne
Copy link
Author

knanne commented Mar 16, 2019

BUG: Python boolean values set in Altair are not converted properly to javascript boolean values. So Python False returns "False" in html vega spec instead of required "false".

Bug reproduced by changing .mark_geoshape() to .mark_geoshape(filled=False) in example https://altair-viz.github.io/gallery/choropleth.html

@tkanngiesser
Copy link

Thanks. Unfortunately it does not show the chart interactively. I've used the example from @jakevdp. Any idea why that is (e.g. because of new Version 3.0.1) ?

@jakevdp
Copy link

jakevdp commented May 13, 2019

Altair 3 outputs mimetype 'application/vnd.vegalite.v3+json' , and requires vega-lite@3 and vega@5.

@tkanngiesser
Copy link

tkanngiesser commented May 21, 2019

I changed the template the following but unfortunately it still does not render the chart in the html file. Any tip would be much appreciated. Thanks!

`{% extends "full.tpl" %}

{% set altair = {'vis_number': 1} %}

{% block header %}

<script src="https://cdn.jsdelivr.net/npm/vega@5"></script> <script src="https://cdn.jsdelivr.net/npm/vega-lite@3"></script> <script src="https://cdn.jsdelivr.net/npm/vega-embed@3"></script>

{{super()}}
{% endblock header %}

{% block data_png scoped %}
{% if 'application/vnd.vegalite.v3+json' in output.data %}
{% elif 'application/vnd.vega.v5+json' in output.data %}
{% else %}
{{super()}}
{% endif %}
{% endblock data_png %}

{% block data_priority scoped %}
{% for mimetype in ('application/vnd.vegalite.v3+json','application/vnd.vega.v5+json') %}
{% if mimetype in output.data %}
{% if altair.update({'vis_number': altair.vis_number+1}) %}{% endif %}


<script type="text/javascript">
var spec = {{ output.data[mimetype] }};
var opt = {"renderer": "canvas", "actions": false};
vegaEmbed("#vis{{cell['execution_count']}}_{{ altair.vis_number }}", spec, opt);
</script>
{% elif loop.index == 1 %}
{{super()}}
{% endif %}
{% endfor %}
{% endblock data_priority %}`

@knanne
Copy link
Author

knanne commented May 28, 2019

@jakevdp Thank you for the input. I have updated the gist to accept mimetype application/vnd.vegalite.v3+json and require vega-lite@3 and vega@5. Also updated at vega/altair#329 (comment)

@tkanngiesser The example used includes the BUG mentioned above

Explanation:

The following Python code

# Create a selection that chooses the nearest point & selects based on x-value
nearest = alt.selection(type='single', nearest=True, on='mouseover',
                        fields=['x'], empty='none')

produces the following JSON in the vega spec

'selection': {'selector001': {'empty': 'none', 'fields': ['x'], 'nearest': True, 'on': 'mouseover', 'resolve': 'global', 'type': 'single'}}

Manual Solution: True needs be changed to true in a text editor (Python variable is titlecase while Javascript variable is lowercase)

I am unaware of an automated solution to this

@ilyasustun
Copy link

@knanne it is not clear what to do from your instructions. What exactly needs to be done with True issue? Are you saying we should check the html in a text editor and change every single True into true? Or something else? I have saved your nbconvert_template_altair.tpl, and although it is able to convert to html, the figures are not interactive.

@knanne
Copy link
Author

knanne commented Jun 2, 2019

Update: I have found a workaround by adding Jinja replace to the template. So var spec = {{ output.data[mimetype] }}; was changed to var spec = {{ output.data[mimetype] | replace("True","true") | replace("False","false") }};

@ilyasustun yes that is what I was suggesting. For this specific issue, manual intervention was* needed.

* The gist above has been updated with a workaround, as well as vega/altair#329 (comment) Please update your local template.

@ilyasustun
Copy link

Ok updated the template file, but still no interactivity. Just plain html file, with no tooltip etc working.

@knanne
Copy link
Author

knanne commented Sep 5, 2019

@ilyasustun the gist has been updated to work with latest version of Altair. Please try again

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