ResMar ResMar - 1 month ago 14
Javascript Question

D3 4.0+ does not create a global d3 variable when imported into Jupyter Notebook

The following will fail with a JavaScript

ReferenceError
:

from IPython.display import HTML, display

display(HTML("""
<script src="https://d3js.org/d3.v4.js"></script>

<script>
console.log(d3);
</script>
"""))


Why is that?

The equivalent D3 version 3.x will work (albeit on the second try, for me):

from IPython.display import HTML, display

display(HTML("""
<script src="https://d3js.org/d3.v3.js"></script>

<script>
console.log(d3);
</script>
"""))


This is the most relevant question/answer I could find on this topic.

Answer

This turned out to be due to an internal change to the way that d3 exports itself. 3.x branch versions of d3 exported all of their internals as global variables (source code); 4.x branch versions no longer do that (source code). A package manager (like require.js) is expected instead now, and exports are piped to that instead.

Further details are in the requisite GitHub issue.

What you should do instead now is something like:

<script src="scripts/require.js"></script>
<script>var d3 = require('d3')</script>

After that, everything should work as expected.

Comments