D3 4.0+ does not create a global d3 variable when

2019-04-09 19:45发布

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.

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-04-09 20:10

I have a solution described here:

http://makeyourowntextminingtoolkit.blogspot.co.uk/2016/09/interactive-d3v4js-in-jupyter-notebook.html

Essentially you need to use require.js .. which is already available through the notebook's own infrastructure.

查看更多
对你真心纯属浪费
3楼-- · 2019-04-09 20:22

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.

查看更多
登录 后发表回答