Javascript d3.js:如何在force布局中更新链接数据时删除节点

Javascript d3.js:如何在force布局中更新链接数据时删除节点,javascript,graph,d3.js,force-layout,Javascript,Graph,D3.js,Force Layout,我正在使用force布局图显示网络,但在更新数据时遇到问题 我已经检查过了,当然还有D3.js中的“修改部队布局”以及“mbostock”的“常规更新模式”(不幸的是,我最多只能发布两个链接…) 我的代码基于“移动专利诉讼”示例,并进行了一些修改和区别。 您可以在此处查看我的完整代码: <!DOCTYPE html> <meta charset="utf-8"> <style> .link { fill: none; stroke: #666

我正在使用force布局图显示网络,但在更新数据时遇到问题

我已经检查过了,当然还有D3.js中的“修改部队布局”以及“mbostock”的“常规更新模式”(不幸的是,我最多只能发布两个链接…)

我的代码基于“移动专利诉讼”示例,并进行了一些修改和区别。 您可以在此处查看我的完整代码:

<!DOCTYPE html>
<meta charset="utf-8">
<style>

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

#licensing {
    fill: green;
}

.link.licensing {
    stroke: green;
}

.link.resolved {
    stroke-dasharray: 0,2 1;
}

circle {
    fill: #ccc;
    stroke: #333;
    stroke-width: 1.5px;
}

text {
    font: 10px sans-serif;
    pointer-events: none;
    text-shadow: 0 1px 0 #fff, 1px 0 0 #fff, 0 -1px 0 #fff, -1px 0 0 #fff;
}

</style>
<body>
    <!-- add an update button -->
    <div id="update">
        <input name="updateButton" type="button" value="Update" onclick="newData()"/>
    </div>
    <script src="http://d3js.org/d3.v3.min.js"></script>
    <script>

    var width = 960,
        height = 500;

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

    var svg = d3.select("body").append("svg")
        .attr("width", width)
        .attr("height", height)
        .style("border", "1px solid black");

    var dataset = [
                 {source: "Microsoft", target: "Amazon", type: "licensing"},
                 {source: "Microsoft", target: "HTC", type: "licensing"},
                 {source: "Samsung", target: "Apple", type: "suit"},
                 {source: "Motorola", target: "Apple", type: "suit"},
                 {source: "Nokia", target: "Apple", type: "resolved"},
                 {source: "HTC", target: "Apple", type: "suit"},
                 {source: "Kodak", target: "Apple", type: "suit"},
                 {source: "Microsoft", target: "Barnes & Noble", type: "suit"},
                 {source: "Microsoft", target: "Foxconn", type: "suit"},
                 {source: "Oracle", target: "Google", type: "suit"},
                 {source: "Apple", target: "HTC", type: "suit"},
                 {source: "Microsoft", target: "Inventec", type: "suit"},
                 {source: "Samsung", target: "Kodak", type: "resolved"},
                 {source: "LG", target: "Kodak", type: "resolved"},
                 {source: "RIM", target: "Kodak", type: "suit"},
                 {source: "Sony", target: "LG", type: "suit"},
                 {source: "Kodak", target: "LG", type: "resolved"},
                 {source: "Apple", target: "Nokia", type: "resolved"},
                 {source: "Qualcomm", target: "Nokia", type: "resolved"},
                 {source: "Apple", target: "Motorola", type: "suit"},
                 {source: "Microsoft", target: "Motorola", type: "suit"},
                 {source: "Motorola", target: "Microsoft", type: "suit"},
                 {source: "Huawei", target: "ZTE", type: "suit"},
                 {source: "Ericsson", target: "ZTE", type: "suit"},
                 {source: "Kodak", target: "Samsung", type: "resolved"},
                 {source: "Apple", target: "Samsung", type: "suit"},
                 {source: "Kodak", target: "RIM", type: "suit"},
                 {source: "Nokia", target: "Qualcomm", type: "suit"}
                 ];

   var path = svg.append("g").selectAll("path"),
       circle = svg.append("g").selectAll("circle"),
       text = svg.append("g").selectAll("text"),
       marker = svg.append("defs").selectAll("marker");

   var nodes = {};

   update(dataset);

   function newData()
   {
        var newDataset = [
                    {source: "Microsoft", target: "Amazon", type: "licensing"},
                    {source: "Microsoft", target: "HTC", type: "licensing"},
                    {source: "Samsung", target: "Apple", type: "suit"},
                    ];

        update(newDataset);
   }

   function update(links)
   {
        // Compute the distinct nodes from the links.
        links.forEach(function(link)
        {
            link.source = nodes[link.source] || (nodes[link.source] = {name: link.source});
            link.target = nodes[link.target] || (nodes[link.target] = {name: link.target});
        });

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

        // -------------------------------

        // Compute the data join. This returns the update selection.
        marker = marker.data(["suit", "licensing", "resolved"]);

        // Remove any outgoing/old markers.
        marker.exit().remove();

        // Compute new attributes for entering and updating markers.
        marker.enter().append("marker")
           .attr("id", function(d) { return d; })
           .attr("viewBox", "0 -5 10 10")
           .attr("refX", 15)
           .attr("refY", -1.5)
           .attr("markerWidth", 6)
           .attr("markerHeight", 6)
           .attr("orient", "auto")
           .append("line") // use ".append("path") for 'arrows'
           .attr("d", "M0,-5L10,0L0,5");

        // -------------------------------

        // Compute the data join. This returns the update selection.
        path = path.data(force.links());

        // Remove any outgoing/old paths.
        path.exit().remove();

        // Compute new attributes for entering and updating paths.
        path.enter().append("path")
           .attr("class", function(d) { return "link " + d.type; })
           .attr("marker-end", function(d) { return "url(#" + d.type + ")"; });

        // -------------------------------

        // Compute the data join. This returns the update selection.
        circle = circle.data(force.nodes());

        // Add any incoming circles.
        circle.enter().append("circle");

        // Remove any outgoing/old circles.
        circle.exit().remove();

        // Compute new attributes for entering and updating circles.
        circle
           .attr("r", 6)
           .call(force.drag);

        // -------------------------------

        // Compute the data join. This returns the update selection.
        text = text.data(force.nodes());

        // Add any incoming texts.
        text.enter().append("text");

        // Remove any outgoing/old texts.
        text.exit().remove();

        // Compute new attributes for entering and updating texts.
        text
           .attr("x", 8)
           .attr("y", ".31em")
           .text(function(d) { return d.name; });
    }

    // Use elliptical arc path segments to doubly-encode directionality.
    function tick()
    {
       path.attr("d", linkArc);
       circle.attr("transform", transform);
       text.attr("transform", transform);
    }

    function linkArc(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;
    }

    function transform(d)
    {
       return "translate(" + d.x + "," + d.y + ")";
    }

    </script>

.链接{
填充:无;
行程:#666;
笔划宽度:1.5px;
}
#许可证{
填充:绿色;
}
.link.licensing{
笔画:绿色;
}
.link.resolved{
笔划数组:0,2 1;
}
圈{
填充:#ccc;
冲程:#333;
笔划宽度:1.5px;
}
正文{
字体:10px无衬线;
指针事件:无;
文本阴影:01px0#fff,1px0#fff,0-1px0#fff,-1px0#fff;
}
可变宽度=960,
高度=500;
var-force=d3.layout.force()
.尺寸([宽度、高度])
.linkDistance(60)
。收费(-300)
.在(“滴答”,滴答)上;
var svg=d3.选择(“正文”).追加(“svg”)
.attr(“宽度”,宽度)
.attr(“高度”,高度)
.样式(“边框”,“1px纯黑”);
变量数据集=[
{来源:“微软”,目标:“亚马逊”,键入:“授权”},
{来源:“Microsoft”,目标:“HTC”,键入:“licensing”},
{来源:“三星”,目标:“苹果”,类型:“西装”},
{来源:“摩托罗拉”,目标:“苹果”,键入:“西服”},
{来源:“诺基亚”,目标:“苹果”,键入:“已解决”},
{来源:“HTC”,目标:“苹果”,键入:“suit”},
{来源:“柯达”,目标:“苹果”,键入:“西装”},
{来源:“Microsoft”,目标:“Barnes&Noble”,键入:“suit”},
{来源:“微软”,目标:“富士康”,键入:“西服”},
{来源:“甲骨文”,目标:“谷歌”,键入:“诉讼”},
{来源:“苹果”,目标:“HTC”,类型:“西装”},
{来源:“Microsoft”,目标:“Inventec”,键入:“suit”},
{来源:“三星”,目标:“柯达”,类型:“已解决”},
{来源:“LG”,目标:“柯达”,类型:“已解决”},
{来源:“RIM”,目标:“Kodak”,键入:“suit”},
{来源:“索尼”,目标:“LG”,类型:“西装”},
{来源:“柯达”,目标:“LG”,类型:“已解决”},
{来源:“苹果”,目标:“诺基亚”,键入:“已解决”},
{来源:“高通”,目标:“诺基亚”,键入:“已解决”},
{来源:“苹果”,目标:“摩托罗拉”,键入:“西装”},
{来源:“微软”,目标:“摩托罗拉”,键入:“诉讼”},
{来源:“摩托罗拉”,目标:“微软”,键入:“诉讼”},
{来源:“华为”,目标:“中兴”,类型:“西装”},
{来源:“爱立信”,目标:“中兴通讯”,键入:“诉讼”},
{来源:“柯达”,目标:“三星”,键入:“已解决”},
{来源:“苹果”,目标:“三星”,类型:“西装”},
{来源:“柯达”,目标:“RIM”,类型:“套装”},
{来源:“诺基亚”,目标:“高通”,键入:“西装”}
];
var path=svg.append(“g”).selectAll(“path”),
圆圈=svg。追加(“g”)。选择全部(“圆圈”),
text=svg.append(“g”)。选择All(“text”),
marker=svg.append(“defs”).selectAll(“marker”);
var节点={};
更新(数据集);
函数newData()
{
var newDataset=[
{来源:“微软”,目标:“亚马逊”,键入:“授权”},
{来源:“Microsoft”,目标:“HTC”,键入:“licensing”},
{来源:“三星”,目标:“苹果”,类型:“西装”},
];
更新(新数据集);
}
功能更新(链接)
{
//从链接计算不同的节点。
links.forEach(函数(link)
{
link.source=节点[link.source]| |(节点[link.source]={name:link.source});
link.target=节点[link.target]| |(节点[link.target]={name:link.target});
});
力
.节点(d3.值(节点))
.链接(links)
.start();
// -------------------------------
//计算数据联接。这将返回更新选择。
marker=marker.data([“诉讼”、“许可”、“已解决]);
//删除所有传出/旧标记。
marker.exit().remove();
//计算用于输入和更新标记的新属性。
marker.enter().append(“marker”)
.attr(“id”,函数(d){return d;})
.attr(“视图框”,“0-5 10”)
.attr(“参考文献”,第15页)
.attr(“参考文献”,-1.5)
.attr(“markerWidth”,6)
.attr(“markerHeight”,6)
.attr(“方向”、“自动”)
.append(“line”)//使用“.append(“path”)表示“箭头”
.attr(“d”,“M0,-5L10,0L0,5”);
// -------------------------------
//计算数据联接。这将返回更新选择。
path=path.data(force.links());
//删除所有传出/旧路径。
path.exit().remove();
//计算用于输入和更新路径的新属性。
path.enter().append(“路径”)
.attr(“类”,函数(d){return“link”+d.type;})
.attr(“marker end”,函数(d){return”url(#“+d.type+”);});
// -------------------------------
//计算数据联接。这将返回更新选择。
circle=circle.data(force.nodes());
//添加任何传入的圆。
circle.enter().append(“circle”);
//删除所有传出/旧圆圈。
circle.exit().remove();
//计算用于输入和更新圆的新属性。
圆圈
.attr(“r”,6)
.呼叫(强制拖动);
// -------------------------------
//计算
<!DOCTYPE html>
<meta charset="utf-8">
<style>

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

#licensing {
    fill: green;
}

.link.licensing {
    stroke: green;
}

.link.resolved {
    stroke-dasharray: 0,2 1;
}

circle {
    fill: #ccc;
    stroke: #333;
    stroke-width: 1.5px;
}

text {
    font: 10px sans-serif;
    pointer-events: none;
    text-shadow: 0 1px 0 #fff, 1px 0 0 #fff, 0 -1px 0 #fff, -1px 0 0 #fff;
}

    </style>
<body>
    <!-- add an update button -->
    <div id="update">
        <input name="updateButton" type="button" value="Update" onclick="newData()"/>
    </div>
    <script src="http://d3js.org/d3.v3.min.js"></script>
    <script>

    var width = 960,
        height = 500;

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

    var svg = d3.select("body").append("svg")
        .attr("width", width)
        .attr("height", height)
        .style("border", "1px solid black");

    var dataset = [
                   {source: "Microsoft", target: "Amazon", type: "licensing"},
                   {source: "Microsoft", target: "HTC", type: "licensing"},
                   {source: "Samsung", target: "Apple", type: "suit"},
                   {source: "Motorola", target: "Apple", type: "suit"},
                   {source: "Nokia", target: "Apple", type: "resolved"},
                   {source: "HTC", target: "Apple", type: "suit"},
                   {source: "Kodak", target: "Apple", type: "suit"},
                   {source: "Microsoft", target: "Barnes & Noble", type: "suit"},
                   {source: "Microsoft", target: "Foxconn", type: "suit"},
                   {source: "Oracle", target: "Google", type: "suit"},
                   {source: "Apple", target: "HTC", type: "suit"},
                   {source: "Microsoft", target: "Inventec", type: "suit"},
                   {source: "Samsung", target: "Kodak", type: "resolved"},
                   {source: "LG", target: "Kodak", type: "resolved"},
                   {source: "RIM", target: "Kodak", type: "suit"},
                   {source: "Sony", target: "LG", type: "suit"},
                   {source: "Kodak", target: "LG", type: "resolved"},
                   {source: "Apple", target: "Nokia", type: "resolved"},
                   {source: "Qualcomm", target: "Nokia", type: "resolved"},
                   {source: "Apple", target: "Motorola", type: "suit"},
                   {source: "Microsoft", target: "Motorola", type: "suit"},
                   {source: "Motorola", target: "Microsoft", type: "suit"},
                   {source: "Huawei", target: "ZTE", type: "suit"},
                   {source: "Ericsson", target: "ZTE", type: "suit"},
                   {source: "Kodak", target: "Samsung", type: "resolved"},
                   {source: "Apple", target: "Samsung", type: "suit"},
                   {source: "Kodak", target: "RIM", type: "suit"},
                   {source: "Nokia", target: "Qualcomm", type: "suit"}
                   ];

    var path = svg.append("g").selectAll("path"),
    circle = svg.append("g").selectAll("circle"),
    text = svg.append("g").selectAll("text"),
    marker = svg.append("defs").selectAll("marker");

    var nodes = {};

    update(dataset);

    function newData()
    {
        var newDataset = [
                         {source: "Microsoft", target: "Amazon", type: "licensing"},
                         {source: "Microsoft", target: "HTC", type: "licensing"},
                         {source: "Samsung", target: "Apple", type: "suit"},
                         ];

        update(newDataset);
    }

    function update(links)
    {
        d3.values(nodes).forEach(function(aNode){ aNode.linkCount = 0;});
            // Reset the link count for all existing nodes by
            // creating an array out of the nodes list, and then calling a function
            // on each node to set the linkCount property to zero.

        // Compute the distinct nodes from the links.
        links.forEach(function(link)
        {
            link.source = nodes[link.source] || (nodes[link.source] = {name: link.source, linkCount:0});    // initialize new nodes with zero links
            link.source.linkCount++;
                // record this link on the source node, whether it was just initialized
                // or already in the list, by incrementing the linkCount property
                // (remember, link.source is just a reference to the node object in the
                // nodes array, when you change its properties you change the node itself.)

            link.target = nodes[link.target] || (nodes[link.target] = {name: link.target, linkCount:0});    // initialize new nodes with zero links

            link.target.linkCount++;
        });

        d3.keys(nodes).forEach(
            // create an array of all the current keys(names) in the node list,
            // and then for each one:

            function (nodeKey)
            {
                if (!nodes[nodeKey].linkCount)
                {
                    // find the node that matches that key, and check it's linkCount value
                    // if the value is zero (false in Javascript), then the ! (NOT) operator
                    // will reverse that to make the if-statement return true,
                    // and the following will execute:

                    delete(nodes[nodeKey]);
                        //this deletes the object AND its key from the nodes array
                 }
             }
         );

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

        // -------------------------------

        // Compute the data join. This returns the update selection.
        marker = marker.data(["suit", "licensing", "resolved"]);

        // Remove any outgoing/old markers.
        marker.exit().remove();

        // Compute new attributes for entering and updating markers.
        marker.enter().append("marker")
            .attr("id", function(d) { return d; })
            .attr("viewBox", "0 -5 10 10")
            .attr("refX", 15)
            .attr("refY", -1.5)
            .attr("markerWidth", 6)
            .attr("markerHeight", 6)
            .attr("orient", "auto")
            .append("line") // use ".append("path") for 'arrows'
            .attr("d", "M0,-5L10,0L0,5");

        // -------------------------------

        // Compute the data join. This returns the update selection.
        path = path.data(force.links());

        // Remove any outgoing/old paths.
        path.exit().remove();

        // Compute new attributes for entering and updating paths.
        path.enter().append("path")
            .attr("class", function(d) { return "link " + d.type; })
            .attr("marker-end", function(d) { return "url(#" + d.type + ")"; });

        // -------------------------------

        // Compute the data join. This returns the update selection.
        circle = circle.data(force.nodes());

        // Add any incoming circles.
        circle.enter().append("circle");

        // Remove any outgoing/old circles.
        circle.exit().remove();

        // Compute new attributes for entering and updating circles.
        circle
            .attr("r", 6)
            .call(force.drag);

        // -------------------------------

        // Compute the data join. This returns the update selection.
        text = text.data(force.nodes());

        // Add any incoming texts.
        text.enter().append("text");

        // Remove any outgoing/old texts.
        text.exit().remove();

        // Compute new attributes for entering and updating texts.
        text
            .attr("x", 8)
            .attr("y", ".31em")
            .text(function(d) { return d.name; });
    }

    // Use elliptical arc path segments to doubly-encode directionality.
    function tick()
    {
        path.attr("d", linkArc);
        circle.attr("transform", transform);
        text.attr("transform", transform);
    }

    function linkArc(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;
    }

    function transform(d)
    {
        return "translate(" + d.x + "," + d.y + ")";
    }

    </script>
links.forEach(function(link)
        {
            link.source = nodes[link.source] 
                          || (nodes[link.source] = {name: link.source});

            link.target = nodes[link.target] 
                          || (nodes[link.target] = {name: link.target});
        });
d3.values(nodes).forEach(function(aNode){ aNode.linkCount = 0;}); 
   //Reset the link count for all existing nodes by
   //creating an array out of the nodes list, and then calling a function
   //on each node to set the linkCount property to zero.
links.forEach(function(link)
    {
     link.source = nodes[link.source] 
                      || (nodes[link.source] = {name: link.source, linkCount:0});
                                    //initialize new nodes with zero links

     link.source.linkCount++;
        // record this link on the source node, whether it was just initialized
        // or already in the list, by incrementing the linkCount property
        // (remember, link.source is just a reference to the node object in the 
        // nodes array, when you change its properties you change the node itself.)

     link.target = /* and then do the same for the target node */
    });
force
    .nodes( d3.values(nodes).filter(function(d){ return d.linkCount;}) )
      //Explanation: d3.values() turns the object-list of nodes into an array.
      //.filter() goes through that array and creates a new array consisting of 
      //the nodes that return TRUE when passed to the callback function.  
      //The function just returns the linkCount of that node, which Javascript 
      //interprets as false if linkCount is zero, or true otherwise.
    .links(links)
    .start();
d3.keys(nodes).forEach(
   //create an array of all the current keys(names) in the node list, 
   //and then for each one:

   function (nodeKey) {
       if (!nodes[nodeKey].linkCount) {
         // find the node that matches that key, and check it's linkCount value
         // if the value is zero (false in Javascript), then the ! (NOT) operator
         // will reverse that to make the if-statement return true, 
         // and the following will execute:

           delete(nodes[nodeKey]); 
             //this deletes the object AND its key from the nodes array
       }

   }//end of function

); //end of forEach method

  /*then add the nodes list to the force layout object as before, 
     no filter needed since the list only includes the nodes you want*/