将D3 v3的力导向图转换为D3 v4库实现遇到了困难?

5
我最近使用v3库创建了我的第一个力导向图,但现在我需要使用D3版本4库创建相同的图表,但是v4中的方法已经发生了巨大变化,现在我在所有force()/drag()方法上都收到错误,这些方法在v4中已不存在。
我的图表基于以下模拟 - http://www.ourd3js.com/wordpress/?p=606 有没有v4库的示例存储库,在那里我可以查看并学习一些函数,以便为此特定图表替换?
编辑:
我的当前代码如下,但我无法完全转换它,例如,节点链接有时非常接近,链接和节点的文本重叠。
<svg width="960" height="600"></svg>

Javascript 代码:

var svg = d3.select("svg"),
    width = +svg.attr("width"),
    height = +svg.attr("height");

var graph = root;

var w = window,
    d = document,
    e = d.documentElement,
    g = d.getElementsByTagName('body')[0],
    x = w.innerWidth || e.clientWidth || g.clientWidth,
    y = w.innerHeight|| e.clientHeight|| g.clientHeight;

var width = x;
var height = y;
var img_w = 24;
var img_h = 24;
var k = Math.sqrt(root.nodes.length / (width * height));

var simulation = d3.forceSimulation()
    .force("link", d3.forceLink().id(function(d) { return d.id; }))
    .force("charge", d3.forceManyBody().strength(-5 / k))
    .force("center", d3.forceCenter(width / 2, height / 2));

  var link = svg.append("g")
                .attr("class", "links")
                .selectAll("line")
                .data(graph.links)
                .enter().append("line");

    var node = svg.append("g")
                    .attr("class", "nodes")
                    .selectAll("circle")
                    .data(graph.nodes)
                    .enter().append("image")
                            .attr("width",img_w)
                            .attr("height",img_h)
                            .attr("xlink:href",function(d){
                                return d.image;
                            })
                            .call(d3.drag()
                    .on("start", dragstarted)
                    .on("drag", dragged)
                    .on("end", dragended));

    var links_text = svg.selectAll(".linetext")
                        .data(graph.links)
                        .enter()
                        .append("text")
                        .attr("class","linetext slds-text-heading--small")
                        .attr("text-anchor", "middle")
                        .text(function(d){
                            return '['+d.relation+']';
                        });

    var nodes_text = svg.selectAll(".nodetext")
                        .data(graph.nodes)
                        .enter()
                        .append("text")
                        .attr("class","nodetext slds-text-heading--label")
                        .attr("text-anchor", "middle")
                        .attr("dx",-20)
                        .attr("dy",20)
                        .text(function(d){
                            return (d.subname!=''?(d.subname+': '):'')+d.name;
                        });

  simulation
      .nodes(graph.nodes)
      .on("tick", ticked);

  simulation.force("link")
            .links(graph.links);

  function ticked() {
    link
        .attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

    links_text
        .attr("x",function(d){ return (d.source.x + d.target.x) / 2; })
        .attr("y",function(d){ return (d.source.y + d.target.y) / 2; });

    node
        .attr("x", function(d) { return d.x; })
        .attr("y", function(d) { return d.y; });

    nodes_text
        .attr("x",function(d){ return d.x + 20 })
        .attr("y",function(d){ return d.y + img_w/2; });
  }


function dragstarted(d) {
  if (!d3.event.active) simulation.alphaTarget(0.3).restart();
  d.fx = d.x;
  d.fy = d.y;
}

function dragged(d) {
  d.fx = d3.event.x;
  d.fy = d3.event.y;
}

function dragended(d) {
  if (!d3.event.active) simulation.alphaTarget(0);
  d.fx = null;
  d.fy = null;
}

JSON数据字符串

  var root = {
  "nodes" : [ {
    "subname" : "",
    "name" : "Telco Power Case",
    "image" : "/node32.png",
    "id" : 0
  }, {
    "subname" : "Contact",
    "name" : "Suman Kumar",
    "image" : "/subnode32.png.png",
    "id" : 1
  }, {
    "subname" : "Contact",
    "name" : "Karla Samuel",
    "image" : "/subnode32.png.png",
    "id" : 2
  }, {
    "subname" : "Account",
    "name" : "Signa Tech",
    "image" : "/subnode32.png.png",
    "id" : 3
  }, {
    "subname" : "",
    "name" : "Maven's Case",
    "image" : "/node32.png",
    "id" : 4
  }, {
    "subname" : "",
    "name" : "Delta Case",
    "image" : "/node32.png",
    "id" : 5
  }, {
    "subname" : "Contact",
    "name" : "T Browney",
    "image" : "/subnode32.png.png",
    "id" : 6
  }, {
    "subname" : "Account",
    "name" : "Presto",
    "image" : "/subnode32.png.png",
    "id" : 7
  }, {
    "subname" : "Contact",
    "name" : "Bob Tannenbaum",
    "image" : "/subnode32.png.png",
    "id" : 8
  }, {
    "subname" : "Account",
    "name" : "Tesla Power",
    "image" : "/subnode32.png.png",
    "id" : 9
  } ],
  "links" : [ {
    "target" : 1,
    "source" : 0,
    "relation" : "Trainee"
  }, {
    "target" : 2,
    "source" : 0,
    "relation" : "Manager"
  }, {
    "target" : 3,
    "source" : 0,
    "relation" : "Technology"
  }, {
    "target" : 1,
    "source" : 0,
    "relation" : "Trainee"
  }, {
    "target" : 2,
    "source" : 0,
    "relation" : "Manager"
  }, {
    "target" : 3,
    "source" : 0,
    "relation" : "Technology"
  }, {
    "target" : 2,
    "source" : 4,
    "relation" : "Expert"
  }, {
    "target" : 2,
    "source" : 5,
    "relation" : "Expert"
  }, {
    "target" : 1,
    "source" : 5,
    "relation" : "Expert"
  }, {
    "target" : 6,
    "source" : 5,
    "relation" : "Trainee"
  }, {
    "target" : 7,
    "source" : 5,
    "relation" : "Technology;New Firm"
  }, {
    "target" : 8,
    "source" : 4,
    "relation" : "Expert"
  }, {
    "target" : 9,
    "source" : 4,
    "relation" : "New Firm"
  }, {
    "target" : 8,
    "source" : 4,
    "relation" : "Expert"
  }, {
    "target" : 9,
    "source" : 4,
    "relation" : "New Firm"
  }, {
    "target" : 6,
    "source" : 5,
    "relation" : "Trainee"
  }, {
    "target" : 7,
    "source" : 5,
    "relation" : "Technology;New Firm"
  } ]
};

唯一能帮助你的方式就是看到你的代码... - Gerardo Furtado
抱歉,我刚刚更新了问题并附上了我的代码集。我已经尝试根据D3版本4的函数进行修改,但是我无法准确地使其正常工作。目前,节点和文本有点重叠。我无法提供节点之间的固定链接/边长,这是我可以使用v3 linkDistance函数提供的。 - VarunC
我正试图跟随这个示例 - http://bl.ocks.org/mbostock/2675ff61ea5e063ede2b5d63c08020c7,但是我无法将我的图像节点居中放置在两个边之间。目前,图像的位置从边/链接的起点开始。 - VarunC
1
linkDistance 现在是 d3.forceLink 上的 distance(距离)属性,因此在您的代码中,应写为 .force("link", d3.forceLink().id(function(d) { return d.id; }).distance(200)) - Mark
非常感谢。我也刚刚自己发现了 :-) ... 现在我正在寻找检测边界并始终将我的节点保持在SVG容器内的方法。这可以做到吗?当节点数量增加时,我的节点有时会超出边界。 - VarunC
1个回答

6
你一次性提出了许多问题,所以让我们在这个问题上保持一点理智。
首先,d3.forceLink现在的linkDistance是distance,所以在你的代码中:
.force("link", d3.forceLink().id(function(d) { return d.id; }).distance(200))

第二步,要使您的图像居中,请在设置其x位置时执行以下操作:
node
  .attr("x", function(d) {
    return (d.x - img_w /2);
  });

第三步,要进行边界检测,您需要自己实现。例如,要固定节点位置,请参考以下代码片段:
node
  .attr("x", function(d) {
    var xPos = (d.x - img_w /2);
    if (xPos < 0) return 0;
    if (xPos > (960 - img_w)) return (960 - img_w);
    return xPos;
  })
  .attr("y", function(d) {
    var yPos = d.y;
    if (yPos < 0) return 0;
    if (yPos > (600 - img_h)) return (600 - img_h);
    return yPos;
  });

现在将同样的方法应用于链接...

这是一些示例代码,我已经开始实施一些修复:

<!DOCTYPE html>
<html>

<head>
  <script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
  <style>
    .links line {
      stroke: #aaa;
    }
    
    .nodes circle {
      pointer-events: all;
      stroke: none;
      stroke-width: 40px;
    }
  </style>
</head>

<body>
  <svg width="960" height="600"></svg>
  <script>
    var root = {
      "nodes": [{
        "subname": "",
        "name": "Telco Power Case",
        "image": "http://lorempixel.com/24/24/",
        "id": 0
      }, {
        "subname": "Contact",
        "name": "Suman Kumar",
        "image": "http://lorempixel.com/24/24/",
        "id": 1
      }, {
        "subname": "Contact",
        "name": "Karla Samuel",
        "image": "http://lorempixel.com/24/24/",
        "id": 2
      }, {
        "subname": "Account",
        "name": "Signa Tech",
        "image": "http://lorempixel.com/24/24/",
        "id": 3
      }, {
        "subname": "",
        "name": "Maven's Case",
        "image": "http://lorempixel.com/24/24/",
        "id": 4
      }, {
        "subname": "",
        "name": "Delta Case",
        "image": "http://lorempixel.com/24/24/",
        "id": 5
      }, {
        "subname": "Contact",
        "name": "T Browney",
        "image": "http://lorempixel.com/24/24/",
        "id": 6
      }, {
        "subname": "Account",
        "name": "Presto",
        "image": "http://lorempixel.com/24/24/",
        "id": 7
      }, {
        "subname": "Contact",
        "name": "Bob Tannenbaum",
        "image": "http://lorempixel.com/24/24/",
        "id": 8
      }, {
        "subname": "Account",
        "name": "Tesla Power",
        "image": "http://lorempixel.com/24/24/",
        "id": 9
      }],
      "links": [{
        "target": 1,
        "source": 0,
        "relation": "Trainee"
      }, {
        "target": 2,
        "source": 0,
        "relation": "Manager"
      }, {
        "target": 3,
        "source": 0,
        "relation": "Technology"
      }, {
        "target": 1,
        "source": 0,
        "relation": "Trainee"
      }, {
        "target": 2,
        "source": 0,
        "relation": "Manager"
      }, {
        "target": 3,
        "source": 0,
        "relation": "Technology"
      }, {
        "target": 2,
        "source": 4,
        "relation": "Expert"
      }, {
        "target": 2,
        "source": 5,
        "relation": "Expert"
      }, {
        "target": 1,
        "source": 5,
        "relation": "Expert"
      }, {
        "target": 6,
        "source": 5,
        "relation": "Trainee"
      }, {
        "target": 7,
        "source": 5,
        "relation": "Technology;New Firm"
      }, {
        "target": 8,
        "source": 4,
        "relation": "Expert"
      }, {
        "target": 9,
        "source": 4,
        "relation": "New Firm"
      }, {
        "target": 8,
        "source": 4,
        "relation": "Expert"
      }, {
        "target": 9,
        "source": 4,
        "relation": "New Firm"
      }, {
        "target": 6,
        "source": 5,
        "relation": "Trainee"
      }, {
        "target": 7,
        "source": 5,
        "relation": "Technology;New Firm"
      }]
    };

    var svg = d3.select("svg"),
      width = +svg.attr("width"),
      height = +svg.attr("height");

    var graph = root;

    var w = window,
      d = document,
      e = d.documentElement,
      g = d.getElementsByTagName('body')[0],
      x = w.innerWidth || e.clientWidth || g.clientWidth,
      y = w.innerHeight || e.clientHeight || g.clientHeight;

    var realWidth = width;
    var width = x;
    var height = y;
    var img_w = 24;
    var img_h = 24;
    var k = Math.sqrt(root.nodes.length / (width * height));

    var simulation = d3.forceSimulation()
      .force("link", d3.forceLink().id(function(d) {
        return d.id;
      }).distance(200))
      .force("charge", d3.forceManyBody().strength(-5 / k))
      .force("center", d3.forceCenter(width / 2, height / 2));

    var link = svg.append("g")
      .attr("class", "links")
      .selectAll("line")
      .data(graph.links)
      .enter().append("line");

    var node = svg.append("g")
      .attr("class", "nodes")
      .selectAll("circle")
      .data(graph.nodes)
      .enter().append("image")
      .attr("width", img_w)
      .attr("height", img_h)
      .attr("xlink:href", function(d) {
        return d.image;
      })
      .call(d3.drag()
        .on("start", dragstarted)
        .on("drag", dragged)
        .on("end", dragended));

    var links_text = svg.selectAll(".linetext")
      .data(graph.links)
      .enter()
      .append("text")
      .attr("class", "linetext slds-text-heading--small")
      .attr("text-anchor", "middle")
      .text(function(d) {
        return '[' + d.relation + ']';
      });

    var nodes_text = svg.selectAll(".nodetext")
      .data(graph.nodes)
      .enter()
      .append("text")
      .attr("class", "nodetext slds-text-heading--label")
      .attr("text-anchor", "middle")
      .attr("dx", -20)
      .attr("dy", 20)
      .text(function(d) {
        return (d.subname != '' ? (d.subname + ': ') : '') + d.name;
      });

    simulation
      .nodes(graph.nodes)
      .on("tick", ticked);

    simulation.force("link")
      .links(graph.links);

    function ticked() {
      link
        .attr("x1", function(d) {
          var xPos = d.source.x;
          if (xPos < 0) return 0;
          if (xPos > (960 - img_w)) return (960 - img_w);
          return xPos;
        })
        .attr("y1", function(d) {
          var yPos = d.source.y;
          if (yPos < 0) return 0;
          if (yPos > (600 - img_h)) return (600 - img_h);
          return yPos;
        })
        .attr("x2", function(d) {
          var xPos = d.target.x;
          if (xPos < 0) return 0;
          if (xPos > (960 - img_w)) return (960 - img_w);
          return xPos;
        })
        .attr("y2", function(d) {
          var yPos = d.target.y;
          if (yPos < 0) return 0;
          if (yPos > (600 - img_h)) return (600 - img_h);
          return yPos;
        });

      links_text
        .attr("x", function(d) {
          var xPos = (d.source.x + d.target.x) / 2;
          if (xPos < 0) return 0;
          if (xPos > (960 - img_w)) return (960 - img_w);
          return xPos;
        })
        .attr("y", function(d) {
          var yPos = (d.source.y + d.target.y) / 2;
          if (yPos < 0) return 0;
          if (yPos > (600 - img_h)) return (600 - img_h);
          return yPos;
        });


      node
        .attr("x", function(d) {
          var xPos = (d.x - img_w /2);
          if (xPos < 0) return 0;
          if (xPos > (960 - img_w)) return (960 - img_w);
          return xPos;
        })
        .attr("y", function(d) {
          var yPos = d.y;
          if (yPos < 0) return 0;
          if (yPos > (600 - img_h)) return (600 - img_h);
          return yPos;
        });

      nodes_text
        .attr("x", function(d) {
          return d.x + 20
        })
        .attr("y", function(d) {
          return d.y + img_w / 2;
        });
    }


    function dragstarted(d) {
      if (!d3.event.active) simulation.alphaTarget(0.3).restart();
      d.fx = d.x;
      d.fy = d.y;
    }

    function dragged(d) {
      d.fx = d3.event.x;
      d.fy = d3.event.y;
    }

    function dragended(d) {
      if (!d3.event.active) simulation.alphaTarget(0);
      d.fx = null;
      d.fy = null;
    }
  </script>
</body>

</html>


谢谢@Mark,你的帮助非常大。我已经按照你的建议使图表看起来不错了。我甚至在标签上添加了一个白色背景矩形,以便标签不会被它们之间的链接覆盖。我向你寻求的最后一条建议是,我们能否引入一个函数来检测标签(节点文本/链接文本)是否重叠? - VarunC
我自己还没有尝试过像这样实现标签,但是这个代码块可能是你想要的。 - ropeladder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接