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]
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]
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>
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.
I will publish the notebook created this time → http://nbviewer.jupyter.org/gist/ssugiyama/29b586b25dc63730eb67ee6c1daefac8
-Rich data visualization with Jupyter Notebook x d3.js -How to execute kernel code from JavaScript on Jupyter notebook
[^ 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