How to create d3.js Collapsible force layout with non tree data?

前端 未结 2 1647
时光取名叫无心
时光取名叫无心 2021-01-14 04:43

I have a d3 force directed layout with data in a similar structure below. Is it possible to apply collapsible force layout such as http://bl.ocks.org/mbostock/1062288 to it?

2条回答
  •  梦毁少年i
    2021-01-14 05:04

    Try this:

        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);
                  }
    

    You should use json file like this:

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

提交回复
热议问题