Testing Altair-Saver

This notebook demonstrates the installation and use of altair-saver. The following was tested in Colab, (and is being sanity checked in Next journal and Deepnote)

it came from here:

https://github.com/altair-viz/altair_saver/blob/master/AltairSaver.ipynb

You can see me trying to run this on deepnote too, to see if the issue is related to nextjournal:

https://deepnote.com/project/Sanity-checking-in-deepnote-Kiih2WH2TH20I7hlPceorw/%2FAltairSaver.ipynb

Off we go…

!pip install -q altair_saver
5.9s

Setup Selenium + Chromedriver

!apt-get -qq update
!apt-get -qq install chromium-chromedriver
17.9s

Setup npm and the Vega CLI

! curl -fsSL https://deb.nodesource.com/setup_12.x | sudo -E bash -
! apt-get update -qq
! apt-get install nodejs -qq
!npm install --silent vega-lite vega-cli canvas
49.2s

Create and save a chart

import altair as alt
from vega_datasets import data
cars = data.cars.url
chart = alt.Chart(cars).mark_bar().encode(
  x=alt.X('Miles_per_Gallon:Q', bin=True),
  y='count()',
)
chart.display()
0.3s
! rm chart.*
0.9s
from altair_saver import save
           
# pdf was removed. the notebook fails if we try it.
for fmt in ['json', 'vg.json', 'html', 'png', 'svg']:
  save(chart, f'chart.{fmt}')
!ls -lh chart.*
1.8s

View saved charts

Here we use a variety of IPython display mechanisms to load and display the saved charts.

from PIL import Image
Image.open("chart.png")
0.1s
from IPython.display import display, SVG
with open("chart.svg") as f:
  display(SVG(f.read()))
0.1s
import json
with open('chart.json') as f:
  display(alt.VegaLite(json.load(f)))
0.6s
import json
from altair import vega
# vega.renderers.enable('colab')
with open('chart.vg.json') as f:
  display(vega.Vega(json.load(f)))
0.2s
from IPython.display import HTML
with open("chart.html") as f:
  html = f.read()
HTML(html)
0.4s
#  - this one doesn't work
# from IPython.display import HTML
# import base64
# with open("chart.pdf", 'rb') as f:
#   pdf_base64 = base64.b64encode(f.read()).decode()
# HTML(f'Right-click and choose "Open In New Tab": <a download="chart.pdf" href="data:application/pdf;base64,{pdf_base64}">chart.pdf</a>')
0.0s

Renderers

Alternatively, you can enable an altair-viewer renderer and display the chart within a notebook as a specific type or set of types.

For example, the following encodes both the vega-lite custom mimetype (which is supported by JupyterLab and other frontends via custom frontend extensions), as well as a PNG fallback that will be displayed in other environments:

alt.renderers.enable('altair_saver', fmts=['vega-lite', 'png'])
chart.display()
0.9s

The content of the output can be confirmed by looking at the _repr_mimebundle_ method, which is the special method used by IPython/Jupyter for rich rendering:

chart._repr_mimebundle_(include=None, exclude=None)
0.8s

Appendix

This repo is mounted by: Python
Runtimes (1)