Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display d3.js visualisation in Jupyter Lab

Tags:

jupyter-lab

I would like to display a d3.js visualisation in Jupyter Lab/JupyterLab. I have been following various web tutorials like this one which often begin

%%javascript
require.config({
    paths: {
        d3: 'https://d3js.org/d3.v5.min'
    }
});

This works in Jupyter Notebook, but in Jupyter Lab I get:

Javascript Error: require is not defined

How can display a d3.js visualisation in Jupyter Lab?

like image 754
RobinL Avatar asked Feb 05 '21 08:02

RobinL


1 Answers

This functionality was added by the Jupyter Lab javascript extension (which is installed by default). You can see a demo notebook here.

The relevant bits are as follows. To add d3.js you need:

%%javascript
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = '//cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js';
    document.head.appendChild(script);
    console.log(window.d3)

and then the following should work:

from IPython.display import Javascript
svg_script = '''
var svg = d3.select(element)
    .append("svg")
    .attr("width", 300)
    .attr("height", 300);    

svg.append("circle")
    .style("stroke", "gray")
    .style("fill", "cyan")
    .attr("r", 130)
    .attr("cx", 150)
    .attr("cy", 150)
    .transition()
        .delay(100)
        .duration(10000)  
        .attr("r", 10)
        .attr("cx", 150)
        .style("fill", "blue"); 
'''

Javascript(svg_script)
like image 63
RobinL Avatar answered Sep 21 '22 17:09

RobinL