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
Setup Selenium + Chromedriver
!apt-get -qq update
!apt-get -qq install chromium-chromedriver
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
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()
! rm chart.*
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.*
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")
from IPython.display import display, SVG
with open("chart.svg") as f:
display(SVG(f.read()))
import json
with open('chart.json') as f:
display(alt.VegaLite(json.load(f)))
import json
from altair import vega
# vega.renderers.enable('colab')
with open('chart.vg.json') as f:
display(vega.Vega(json.load(f)))
from IPython.display import HTML
with open("chart.html") as f:
html = f.read()
HTML(html)
# - 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>')
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()
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)