Linking python and JavaScript with jupyter notebook

Introduction

With jupyter notebook, a series of flow from data analysis to visualization is possible with python alone, but if you look at the high expressiveness and interactivity of D3.js, visualization is with JavaScript. I think there will be many cases. Therefore, I would like to introduce how to prepare the data in python and pass it to JavaScript.

In the following explanation, we will use a package that executes and displays D3.js code on a jupyter notebook called py_d3, but it is not limited to D3.js. JavaScript can be executed. [^ 1]

Setup of py_d3

pip install py_d3

You can install it with. To use the function, write as follows at the beginning of the notebook.

%load_ext py_d3

If you write %% d3 at the beginning of the cell, the code in that cell will be interpreted as HTML and JavaScript.

For details, please refer to this article. [^ 2]

Preparation

The cooperation uses the function of the IPython.display.HTML package, but it is difficult to use as it is, so I will define the following JavaScript function and wrap it. Execute it in the cell immediately after `` `% load_ext py_d3```. It is good to register in snippets etc.

%%d3
<script>
function pyexec(command) {
    return new Promise(res => {
        IPython.notebook.kernel.execute(command,
            {iopub: {
                output: 
                    out => res(JSON.parse(eval(out.content.data["text/plain"])))
            }}, 
            {silent: false});
    });
}
</script>

Cooperation

Pass the python code to execute as a string to the pyexec function above. On the python side, please return the value in json format.

For example, define the function on the python side as follows.

import json
import numpy as np
def get_data(count):
    return json.dumps((np.random.rand(count)*10).tolist())

The JavaScript side is described as follows. Describe the process to be performed after receiving the data in then after pyexec. This time I'm running a simple sample from the D3.js tutorial.

%%d3
<g></g>
<style>
element {
    height: 25px;
}
div.bar {
    display: inline-block;
    width: 20px;
    height: 75px;
    margin-right: 2px;
    background-color: teal;
}
</style>

<script>
pyexec("get_data(7)")
.then(dataset => {
    d3.select("g").selectAll("div")
    .data(dataset)
    .enter()
    .append("div")
    .attr("class", "bar")
    .style("height", function(d) {
        let barHeight = d * 5;
        return barHeight + "px";
    });
});
</script>

Then the following graph will be drawn on the notebook.

スクリーンショット 2017-06-12 18.46.40.png

I will publish the notebook created this time → http://nbviewer.jupyter.org/gist/ssugiyama/29b586b25dc63730eb67ee6c1daefac8

reference

-Rich data visualization with Jupyter Notebook x d3.js -How to execute kernel code from JavaScript on Jupyter notebook

footnote

[^ 1]: It is possible to link with only the standard IPython.display.HTML package without using py_d3, but since it is necessary to write JavaScript and HTML code in the character string and escaping etc. is troublesome, it is in the cell We recommend py_d3, which allows you to write JavaScript and HTML directly.

[^ 2]: However, the method of loading py_d3 has been changed from the description in this article, so please use % load_ext py_d3.

Recommended Posts

Linking python and JavaScript with jupyter notebook
3 Jupyter notebook (Python) tricks
Interactively display algebraic curves with Python and Jupyter
Virtual environment construction with Docker + Flask (Python) + Jupyter notebook
Programming with Python and Tkinter
Encryption and decryption with Python
Python and hardware-Using RS232C with Python-
Use Cython with Jupyter Notebook
Play with Jupyter Notebook (IPython Notebook)
[Windows] [Python3] Install python3 and Jupyter Notebook (formerly ipython notebook) on Windows
Try running Python with Try Jupyter
python with pyenv and venv
Comparison of CoffeeScript with JavaScript, Python and Ruby grammar
python3.8 venv environment jupyter notebook
Works with Python and R
Communicate with FX-5204PS with Python and PyUSB
Shining life with Python and OpenCV
Allow external connections with jupyter notebook
Formatting with autopep8 on Jupyter notebook
Robot running with Arduino and python
Install Python 2.7.9 and Python 3.4.x with pip.
Snippet settings for python jupyter notebook
Neural network with OpenCV 3 and Python 3
AM modulation and demodulation with python
[Python] font family and font with matplotlib
Scraping with Node, Ruby and Python
Python memo Anaconda x Jupyter Notebook
Visualize decision trees with jupyter notebook
Make a sound with Jupyter notebook
Scraping with Python, Selenium and Chromedriver
Scraping with Python and Beautiful Soup
Generate Jupyter notebook ".ipynb" in Python
JSON encoding and decoding with python
Hadoop introduction and MapReduce with Python
[GUI with Python] PyQt5-Drag and drop-
Jupyter Notebook: 4 banal tips and tricks
Reading and writing NetCDF with Python
Use markdown with jupyter notebook (with shortcut)
Add more kernels with Jupyter Notebook
I played with PyQt5 and Python3
Convenient analysis with Pandas + Jupyter notebook
Easy to use Jupyter notebook (Python3.5)
Reading and writing CSV with Python
Compare Python and JavaScript array loops
Multiple integrals with Python and Sympy
Coexistence of Python2 and 3 with CircleCI (1.0)
Easy modeling with Blender and Python
Sugoroku game and addition game with python
FM modulation and demodulation with Python
How to batch start a python program created with Jupyter notebook
Operate Jupyter with REST API to extract and save Python code
How to build Python and Jupyter execution environment with VS Code
Communicate between Elixir and Python with gRPC
Data pipeline construction with Python and Luigi
Calculate and display standard weight with python
Differences in authenticity between Python and JavaScript
Use nb extensions with Anaconda's Jupyter notebook
Monitor Mojo outages with Python and Skype
Memory leak in Python Jupyter Lab (Notebook)?
Build Jupyter Lab (Python) environment with Docker
FM modulation and demodulation with Python Part 3