【问题标题】:how to vary distance between d3 nodes in force layout如何在力布局中改变 d3 节点之间的距离
【发布时间】:2013-02-18 13:24:02
【问题描述】:

我在 d3 中搜索了很多可视化。我能够从数据库中可视化我的数据。现在,我想改变不同 d3 节点之间的距离。有一个函数 force.linkdistance() 用于指定节点之间的距离。目前我提供 100 的恒定距离。我想根据数据库中的列来改变每个链接的距离。这是一个数字列。我也附上我的代码。如果有人可以,请帮忙。

    var okCounter=0;
var width = 960,
height = 500;

console.log("still ok here:",okCounter++);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);
console.log("still ok here:",okCounter++);
var force = d3.layout.force()
    .gravity(.05)
    .distance(100)
    .charge(-100)
    .size([width, height]);
console.log("still ok here:",okCounter++);
d3.json("getdata.php", function(error,json) {
   force
      .nodes(json.nodes)
      .links(json.links)
      .start();
console.log("still ok here:",okCounter++);
  var link = svg.selectAll(".link")
      .data(json.links)
      .enter().append("path")
      .attr("class", "link");
console.log("still ok here:",okCounter++);
  var node = svg.selectAll(".node")
      .data(json.nodes)
    .enter().append("g")
      .attr("class", "node")
     // .call(force.drag);
console.log("still ok here:",okCounter++);
  node.append("image")
      .attr("xlink:href", "http://www.clker.com/cliparts/5/6/3    /a/1194984675331456830utente_singolo_architett_01.svg.med.png")
      .attr("x", -8)
      .attr("y", -8)
      .attr("width", 24)
      .attr("height", 24);
console.log("still ok here:",okCounter++);
  node.append("text")
      .attr("dx", 24)
      .attr("dy", ".35em")
      .text(function(d) { return d.name });
console.log("still ok here:",okCounter++);
  force.on("tick", function() {
    link.attr("d", function(d) {
var dx = d.target.x - d.source.x,
    dy = d.target.y - d.source.y,
    dr = Math.sqrt(dx * dx + dy * dy); 
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " +     d.target.x + "," + d.target.y;
});
console.log("still ok here:",okCounter++);
    node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")";   });
 });
});</script> 

【问题讨论】:

    标签: javascript d3.js force-layout


    【解决方案1】:

    如果您希望 force.linkDistance 发生变化,请使用函数而不是常量。

    如果距离是一个常数,那么所有链接的距离都是相同的。否则,如果距离是一个函数,则对每个链接(按顺序)评估该函数,传递链接及其索引,this 上下文作为强制布局;然后使用该函数的返回值来设置每个链接的距离。每当布局开始时,都会评估该函数。

    (来自https://github.com/d3/d3-3.x-api-reference/blob/master/Force-Layout.md#linkDistance

    您可能还希望尝试将函数传递给force.linkStrength,尽管我怀疑效果会很微妙(我自己还没有尝试过)。

    【讨论】:

      【解决方案2】:
      var force = d3.layout.force()
          .linkDistance(function(d) { 
                return(/* whatever computation you want the distance of each link to be */); 
          }
          .start();
      

      【讨论】:

        猜你喜欢
        • 2018-12-29
        • 2015-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-04
        相关资源
        最近更新 更多