Exporting Jupyter notebooks with Plotly graphs

Friday, 28 June 2019

Exporting Jupyter notebooks with Plotly graphs

If it is a small project or analysis, I opt for Jupyter notebook rather than an IDE such as PyCharm, which is great for large projects, but not such much for a small analyse as go project. Plotly is my goto for graphs —I proselytise about it. The advantage is that it is a wrapper for a JS library which allows interactive. However, in my system at least, using the plotly.offline.iplot plotter, when I export it as a HTML an error is thrown due to require not being set up correction. This is easily fixed.

To fix it, one can add to a new notebook cell the following:

The %% is cell-magic to mark that the cell is JavaScript as opposed to Python or Julia and it tells require.js which CDN to use.

Jupyter Notebooks saves the state of the output cells so that they are preserved when reloaded —the variables in the Python kernel are not preseved as that would require them to be serialisable etc. and would cause more drama that it is worth. Curiously, this means that when the Javascript cell is added and run, it is the same as if the Python code display(HTML(<script>JS code to add</script>)) which adds it to the output_area —and saves the state. If said JavaScript alters the DOM that state is not saved.

Bonus

Another thing one can is get the HTML code from the output_area which contains the Plotly chart and add it to whatever target HTML page, say this blog post:

To do this, one can do the following in a cell with the %%javascript cell magic to output, and, additionally, one can replace out the require.js function and simply add a good old fashioned script tag pointing to the CDN at the top of the page.

<script src="https://cdn.plot.ly/plotly-1.2.0.min.js"></script>

No comments:

Post a Comment