如何创建具有非树形数据的d3.js可折叠强制布局?

3

我使用的是d3力导向图,数据结构与下面类似。是否可以像这个例子中一样应用可折叠力导向布局?我希望能够在单击节点时实现节点的展开和折叠。

{
  "nodes": [
    {"x": 469, "y": 410},
    {"x": 493, "y": 364},
    {"x": 442, "y": 365},
    {"x": 467, "y": 314},
  ],
  "links": [
    {"source":  0, "target":  1},
    {"source":  1, "target":  2},
    {"source":  2, "target":  0},
    {"source":  1, "target":  3},
    {"source":  3, "target":  2},
  ]
}
2个回答

3
如果我理解正确,可能这就是你要找的。我编辑了你提供的演示。现在,当源节点折叠时,我们遍历所有边缘并查找它有边缘连接到的其他节点。
对于每个源节点具有边缘连接的目标节点,我们将其折叠计数增加。如果节点具有大于零的折叠计数,则不显示该节点。
当我们展开节点时,我们做同样的事情,只是从折叠计数中减去。
由于我们不在树中,因此需要此折叠计数,因为节点可以具有多个应该导致它们折叠的节点。
我使其适用于定向图,尽管我不确定这是否是您想要的。
让我知道你的想法!
我使用的json:
  {
    "nodes": [
     {"x": 469, "y": 410},
     {"x": 493, "y": 364},
     {"x": 442, "y": 365},
     {"x": 467, "y": 314}
 ],
     "links": [
      {"source":  0, "target":  1},
      {"source":  1, "target":  2},
      {"source":  2, "target":  0},
      {"source":  1, "target":  3},
      {"source":  3, "target":  2}
  ]
 }

修改后的教程代码:

<!DOCTYPE html>
<meta charset="utf-8">
<title>Force-Directed Graph</title>
<style>

.node {
  cursor: pointer;
  stroke: #3182bd;
  stroke-width: 1.5px;
}

.link {
  fill: none;
  stroke: #9ecae1;
  stroke-width: 1.5px;
}

</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>

var width = 960,
    height = 500,
    root;

var force = d3.layout.force()
    .size([width, height])
    .on("tick", tick);

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

//Added markers to indicate that this is a directed graph
svg.append("defs").selectAll("marker")
    .data(["arrow"])
    .enter().append("marker")
    .attr("id", function(d) { return d; })
    .attr("viewBox", "0 -5 10 10")
    .attr("refX", 15)
    .attr("refY", -1.5)
    .attr("markerWidth", 4)
    .attr("markerHeight", 4)
    .attr("orient", "auto")
    .append("path")
    .attr("d", "M0,-5L10,0L0,5");

var link = svg.selectAll(".link"),
    node = svg.selectAll(".node");

d3.json("graph.json", function(json) {
  root = json;
  //Give nodes ids and initialize variables
  for(var i=0; i<root.nodes.length; i++) {
    var node = root.nodes[i];
    node.id = i;
    node.collapsing = 0;
    node.collapsed = false;
  }
  //Give links ids and initialize variables
  for(var i=0; i<root.links.length; i++) {
    var link = root.links[i];
    link.source = root.nodes[link.source];
    link.target = root.nodes[link.target];
    link.id = i;
  }

  update();
});

function update() {
  //Keep only the visible nodes
  var nodes = root.nodes.filter(function(d) {
    return d.collapsing == 0;
  });
  var links = root.links;
  //Keep only the visible links
  links = root.links.filter(function(d) {
    return d.source.collapsing == 0 && d.target.collapsing == 0;
  });

  force
      .nodes(nodes)
      .links(links)
      .start();

  // Update the links…
  link = link.data(links, function(d) { return d.id; });

  // Exit any old links.
  link.exit().remove();

  // Enter any new links.
  link.enter().insert("line", ".node")
      .attr("class", "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; })
      .attr("marker-end", "url(#arrow)");

  // Update the nodes…
  node = node.data(nodes, function(d){ return d.id; }).style("fill", color);

  // Exit any old nodes.
  node.exit().remove();

  // Enter any new nodes.
  node.enter().append("circle")
      .attr("class", "node")
      .attr("cx", function(d) { return d.x; })
      .attr("cy", function(d) { return d.y; })
      .attr("r", function(d) { return Math.sqrt(d.size) / 10 || 4.5; })
      .style("fill", color)
      .on("click", click)
      .call(force.drag);
}

function tick() {
  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; });

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

// Color leaf nodes orange, and packages white or blue.
function color(d) {
  return d.collapsed ? "#3182bd" : d.children ? "#c6dbef" : "#fd8d3c";
}

// Toggle children on click.
function click(d) {
  if (!d3.event.defaultPrevented) {
    //check if link is from this node, and if so, collapse
    root.links.forEach(function(l) {
      if(l.source.id == d.id) {
        if(d.collapsed){
          l.target.collapsing--;
        } else {
          l.target.collapsing++;
        }
      }
    });
    d.collapsed = !d.collapsed;
  }
  update();
}

</script>

1
谢谢你提供的代码。它按预期工作。这里有额外的要求,我需要按节点ID而不是索引链接节点,可以参考这个例子https://dev59.com/UmAg5IYBdhLWcg3wFHuF‌​‌​me-instead-of-index。此外,我想让它们绑定到SVG框并在节点上添加文本。我应该如何修改代码? - CY-
@CY,你找到答案了吗? - Mcestone
1
有人知道如何在d3.js v4中实现吗? - deathlock

0

试试这个:

    var width = 960,height = 500;

    var force = d3.layout.force().size([width, height]).charge(-400)
                .linkDistance(40)
                .on("tick", tick);

         var drag = force.drag().on("dragstart", dragstart);

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

           var link = svg.selectAll(".link"),
                  node = svg.selectAll(".node");

            d3.json("graph.json", function(error, graph) {
                     force.nodes(graph.nodes).links(graph.links)
                         .start();

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

                  node = node.data(graph.nodes)
                 .enter().append("circle")
                 .attr("class", "node")
                 .attr("r", 12)
                 .call(drag);
         });

         function tick() {
              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; });

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



           function dragstart(d) {
                  d3.select(this).classed("fixed", d.fixed = true);
              }

你应该像这样使用json文件:

graph.json

      {
        "nodes": [
         {"x": 469, "y": 410},
         {"x": 493, "y": 364},
         {"x": 442, "y": 365},
         {"x": 467, "y": 314},
     ],
         "links": [
          {"source":  0, "target":  1},
          {"source":  1, "target":  2},
          {"source":  2, "target":  0},
          {"source":  1, "target":  3},
          {"source":  3, "target":  2},
      ]
     }

谢谢您的回答,但我正在寻找可折叠和可展开的节点,需要点击才能实现。 - CY-
更像 http://bl.ocks.org/mbostock/1062288,但我的JSON定义不同。 - CY-

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