简体   繁体   中英

d3 svg path attr d assignment fails in Jupyter Notebook

In working on a directed graph visualization in d3 I followed Martin Graham's jsfiddle example here to create bezier arcs for multiple links between two nodes. This worked a treat and I'm grateful for his guidance. The current state of development of my working example can be seen here . The d3 code is right in the HTML in <script> tags. The function for generating those arcs looks like this:

  function linkArc(d,i,lnks) {
    var dx = d.target.x - d.source.x,
        dy = d.target.y - d.source.y;
    var qx = dy /  6 * d.linknum,
        qy = -dx / 6 * d.linknum;
    var qx1 = (d.source.x + (dx / 2)) + qx,
        qy1 = (d.source.y + (dy / 2)) + qy;

    return `M${d.source.x} ${d.source.y}
            C${d.source.x} ${d.source.y}, ${qx1} ${qy1}, ${d.target.x} ${d.target.y}`;
  };

And it is called from within the drawGraph function like this:

simulation.on("tick", () => {
    link.attr("d", linkArc);
    ...etc...
 

Well and good, this works. But what I'm aiming at is deploying this visualization in the context of a Jupyter Notebook, and in that context when d3 tries to render those links, I get a javascript error on each tick() saying Error: <path> attribute d: Expected number, "MNaN NaN\n …".

linkArc() does return a string, but I'm hoping someone wiser in the ways of Jupyter and/or d3 can explain to me why that string works in one context, but not the other.

any thoughts?

The solution to this puzzle is almost too embarrassing to recount, but in the unlikely event that anyone was mildly curious, I finally realized that the x and y coordinates of the nodes were not being calculated because they depend on width and height of the svg element, and those variables were declared outside the drawGraph function that I had moved, unrevised, into the javascript module imported by the Notebook via require.js .

This was due, in part, to my complete unfamiliarity with how require.js works, and to the fact that the error message told me only about the consequence of my oversight rather than its cause. Let this be a lesson to me: variables have SCOPE. And part of the whole point of javascript modules is to control and confine scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM