gpoore / codebraid

Live code in Pandoc Markdown
BSD 3-Clause "New" or "Revised" License
367 stars 13 forks source link

Support for Altair plots in Jupyter mode #22

Closed sergei-mironov closed 4 years ago

sergei-mironov commented 4 years ago

Hi. I hoped that I can display Altair plots in Jupyter mode just like we plot Matplotlib. Unfortunately, I can't get a working solution up to this moment.

For example, the code

 ```{.python .cb.nb jupyter_kernel=python3}
import altair as alt
alt.renderers.enable('notebook')
import pandas as pd
from pandas import DataFrame
import matplotlib.pyplot as plt
%matplotlib inline

df=DataFrame({'step':[0,1,2,3], 'value':[0,1,2,3]})
x=alt.Chart(df).mark_line().encode(x='step', y='value')
x.display() # Not sure, putting just `x` here produces the same result

outputs just

<vega.vegalite.VegaLite at 0x7fe448947fd0>



but not an image.

Could you please comment on what may be wrong and do we have a chance to make this work?

Note, I'm using current HEAD version `pip install git+https://github.com/gpoore/codebraid@011464539bfb09b8611c8aef0d543532cea958bf`
gpoore commented 4 years ago

It looks like this is giving the plot as javascript plus plain text. Codebraid doesn't have support for dealing with javascript, so it falls back to plain text. If you can get the plot in png or jpeg, that would work. It might also be possible to add support for javascript output...it could probably just be included in the intermediate markdown via a raw html block (```{=html} ...).

sergei-mironov commented 4 years ago

Thanks for the comment! Indeed, it turns out that Altair by default does output urls pointing to images rather than images themselves. In order to print images in-line we have to install an extension called altair_saver. Funny, but it seems they capture PNGs by producing webpages first, and then by grabbing them with either seleneum or nodejs. Below is the docker snippet I use to install everything required to follow the nodejs-way. Anyway, the figures looks great.

apt-get install -y libssl1.0-dev nodejs-dev node-gyp npm
npm install -g vega-lite vega-cli canvas
pip3 install altair altair_saver altair_viewer vega

The codebraid part becomes:

```{.python .cb.nb jupyter_kernel=python3}
import altair as alt
import altair_saver
alt.renderers.enable('altair_saver', fmts=['vega-lite', 'png'])
%matplotlib inline
import pandas as pd
df=pd.DataFrame({'step':[0,1,2,3], 'value':[0,1,2,3]})
x=alt.Chart(df).mark_line().encode(x='step', y='value')
x