score:5

Accepted answer

Let me give first a working example (tested on ijavascript@5.0.19, jsdom@9.12.0 and d3@4.8.0) and then some clarifications:

var jsdom = require("jsdom");
global.document = jsdom.jsdom();

var d3 = require("d3");

var svg = d3.select(document.body).append("svg");

svg.append("rect")
    .attr("width", 80)
    .attr("height", 80)
    .style("fill", "orange");

$$.svg(svg.node().outerHTML);

screenshot from 2017-04-20 09-32-53

This solution:

  • uses the DOM provided by jsdom.

  • uses d3 to create an <svg> node and append a <rect>

  • uses outerHTML to get the string representation of the <svg> node created in the previous steps

  • and finally instructs IJavascript to return this string to the Jupyter notebook as an SVG result.

In theory, IJavascript could inject javascript code into the Jupyter notebook (to manipulate its DOM), but this code may not run (depending on the security policies of the Jupyter frontend).


Since your interest is scientific analysis, you may be interested in a module I published recently: ijavascript-plotly.


I know this answer skims through many concepts. Please, use the comments below, if you need me to update the answer and explain anything further.

score:2

A similar approach to render D3 in Jupyter:

var d3 = require("d3");
var jsdom = require("jsdom");

var dom = new jsdom.JSDOM("<svg></svg>",{QuerySelector:true});

var svg = dom.window.document.querySelector("svg");

d3.select(svg)
    .append("rect")
    .attr("width", 80)
    .attr("height", 80)
    .style("fill", "orange");

$$.html(dom.serialize());

Related Query