如何使用非树数据创建d3.js可折叠力布局?

如何使用非树数据创建d3.js可折叠力布局?,d3.js,tree,data-visualization,force-layout,directed-graph,D3.js,Tree,Data Visualization,Force Layout,Directed Graph,我有一个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, "targe

我有一个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},
  ]
}
试试这个:

    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},
      ]
     }

如果我理解正确,也许这就是你要找的。我编辑了你链接到的演示。现在,当一个源节点被折叠时,我们迭代所有的边,寻找它有边的其他节点

对于源节点有一条边的每个目标节点,我们增加它的折叠计数。如果节点的折叠计数大于零,则不会显示该节点

当我们解压一个节点时,我们会做同样的事情,只是我们会从折叠计数中递减

我们需要这个折叠计数,因为我们不在树中,节点可以有多个节点,这会导致它们折叠

我为有向图做了这项工作,虽然我不确定这是你想要的

让我知道你的想法

我使用的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>

力有向图
.节点{
光标:指针;
行程:#3182bd;
笔划宽度:1.5px;
}
.链接{
填充:无;
行程:#9ecae1;
笔划宽度:1.5px;
}
可变宽度=960,
高度=500,
根;
var-force=d3.layout.force()
.尺寸([宽度、高度])
.在(“滴答”,滴答)上;
var svg=d3.选择(“正文”).追加(“svg”)
.attr(“宽度”,宽度)
.attr(“高度”,高度);
//添加标记以指示这是一个有向图
svg.append(“defs”).selectAll(“marker”)
.数据([“箭头”])
.enter().append(“标记”)
.attr(“id”,函数(d){return d;})
.attr(“视图框”,“0-5 10”)
.attr(“参考文献”,第15页)
.attr(“参考文献”,-1.5)
.attr(“markerWidth”,4)
.attr(“markerHeight”,4)
.attr(“方向”、“自动”)
.append(“路径”)
.attr(“d”,“M0,-5L10,0L0,5”);
var link=svg.selectAll(“.link”),
node=svg.selectAll(“.node”);
d3.json(“graph.json”,函数(json){
root=json;
//给节点ID并初始化变量

对于(var i=0;我感谢您的回答,但我正在查找单击时可折叠和可扩展的节点。更像,但我的json定义不同。感谢您的代码。它按预期工作。这里的其他要求是,我需要通过节点ID链接节点,而不是按照以下示例中的索引链接节点。此外,我希望将它们绑定到svg框并向节点添加文本。我应该如何修改代码?@CY-你找到过答案吗?有人知道如何在d3.js v4中进行修改吗?