javascript - 如何根据d3.js图形库中的节点id连接边与节点

标签 javascript json d3.js

此代码可以与下面给出的 JSON data1 对象一起正常工作,但我希望此代码可以与此 new_json 对象一起使用。我想在节点 id 上建立链接。有什么帮助吗?

 var new_json = {{"nodes": [{ "id": 124587, "name": "paper1", "citation": 5, "group": 1 },
{ "id": 178456, "name": "paper2", "citation": 8, "group": 2 }],
"links": [{ "source": 124587, "target": 178456, "name": "A-B-1", "value": 8 }]};

function load_graph(text) {
            var color = d3.scale.category20();           
            var data1 = {
                "nodes": [
                    { "id": 0, "name": "paper1", "citation": 5, "group": 1 },
                    { "id": 1, "name": "paper2", "citation": 8, "group": 2 },
                    { "id": 2, "name": "paper3", "citation": 12, "group": 3 },
                    { "id": 3, "name": "paper4", "citation": 25, "group": 4 },
                    { "id": 4, "name": "paper5", "citation": 15, "group": 5 },
                    { "id": 5, "name": "paper6", "citation": 5, "group": 1 },
                    { "id": 6, "name": "paper7", "citation": 8, "group": 2 },
                    { "id": 7, "name": "paper8", "citation": 12, "group": 3 },
                    { "id": 8, "name": "paper9", "citation": 25, "group": 4 },
                    { "id": 9, "name": "paper10", "citation": 15, "group": 5 }
                ],
                "links": [
                    { "source": 0, "target": 1, "name": "A-B-1", "value": 8 },
                    { "source": 0, "target": 1, "name": "A-B-2", "value": 24 },
                    { "source": 0, "target": 2, "name": "A-C-1", "value": 12 },
                    { "source": 0, "target": 2, "name": "A-C-3", "value": 44 },
                    { "source": 2, "target": 3, "name": "A-D-1", "value": 11 },
                    { "source": 2, "target": 3, "name": "A-D-2", "value": 35 },
                    { "source": 2, "target": 4, "name": "A-E-1", "value": 16 },
                    { "source": 2, "target": 4, "name": "A-E-5", "value": 30 },
                    { "source": 4, "target": 5, "name": "A-B-1", "value": 8 },
                    { "source": 4, "target": 5, "name": "A-B-2", "value": 24 },
                    { "source": 5, "target": 6, "name": "A-C-1", "value": 12 },
                    { "source": 5, "target": 6, "name": "A-C-3", "value": 44 },
                    { "source": 5, "target": 7, "name": "A-D-1", "value": 11 },
                    { "source": 5, "target": 7, "name": "A-D-2", "value": 35 },
                    { "source": 7, "target": 8, "name": "A-E-1", "value": 16 },
                    { "source": 7, "target": 8, "name": "A-E-5", "value": 30 },
                    { "source": 8, "target": 3, "name": "A-C-1", "value": 12 },
                    { "source": 8, "target": 3, "name": "A-C-3", "value": 44 },
                    { "source": 8, "target": 9, "name": "A-D-1", "value": 11 },
                    { "source": 8, "target": 9, "name": "A-D-2", "value": 35 }
                ]
            };

            // used to store the number of links between two nodes. 
            // mLinkNum[data.links[i].source + "," + data.links[i].target] = data.links[i].linkindex;
            var mLinkNum = {};

            // sort links first
            sortLinks();

            // set up linkIndex and linkNumer, because it may possible multiple links share the same source and target node
            setLinkIndexAndNum();

            var w = 960,
                h = 500;

            var force = d3.layout.force()
                          .nodes(d3.values(data1.nodes))
                          .links(data1.links)
                          .size([w, h])
                          .linkDistance(200)
                          .charge(-300)
                          .on("tick", tick)
                          .start();

            var svg = d3.select(".graphContainer").append("svg:svg")
                        .attr("width", w)
                        .attr("height", h);

            var path = svg.append("svg:g")
                          .selectAll("line")
                          .data(force.links())
                          .enter().append("svg:path")
                          .attr("class", "link")
                          .style("stroke-width", function (d) { return Math.sqrt(d.value); });


            var circle = svg.append("svg:g")
                            .selectAll("circle")
                            .data(force.nodes())
                            .enter().append("svg:circle")
                            .attr("r", function (d) { return (d.citation); })
                            .style("fill", function (d) { return color(d.group); })
                            .call(force.drag);

            var text = svg.append("svg:g")
                          .selectAll("g")
                          .data(force.nodes())
                          .enter().append("svg:g");

            // A copy of the text with a thick white stroke for legibility.
            text.append("svg:text")
                .attr("x", 8)
                .attr("y", ".31em")
                .attr("class", "shadow")
                .text(function (d) { return d.name; });

            text.append("svg: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", function (d) {
                    var dx = d.target.x - d.source.x,
                        dy = d.target.y - d.source.y,
                        dr = Math.sqrt(dx * dx + dy * dy);
                    // get the total link numbers between source and target node
                    var lTotalLinkNum = mLinkNum[d.source.id + "," + d.target.id] || mLinkNum[d.target.id + "," + d.source.id];
                    if (lTotalLinkNum > 1) {
                        // if there are multiple links between these two nodes, we need generate different dr for each path
                        dr = dr / (1 + (1 / lTotalLinkNum) * (d.linkindex - 1));
                    }
                    // generate svg path
                    return "M" + d.source.x + "," + d.source.y +
                        "A" + dr + "," + dr + " 0 0 1," + d.target.x + "," + d.target.y +
                        "A" + dr + "," + dr + " 0 0 0," + d.source.x + "," + d.source.y;
                });

                // Add tooltip to the connection path
                path.append("svg:title")
                    .text(function (d, i) { return d.name; });

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

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

            // sort the links by source, then target
            function sortLinks() {
                data.links.sort(function (a, b) {
                    if (a.source > b.source) {
                        return 1;
                    }
                    else if (a.source < b.source) {
                        return -1;
                    }
                    else {
                        if (a.target > b.target) {
                            return 1;
                        }
                        if (a.target < b.target) {
                            return -1;
                        }
                        else {
                            return 0;
                        }
                    }
                });
            }

            //any links with duplicate source and target get an incremented 'linknum'
            function setLinkIndexAndNum() {
                for (var i = 0; i < data.links.length; i++) {
                    if (i != 0 &&
                        data.links[i].source == data.links[i - 1].source &&
                        data.links[i].target == data.links[i - 1].target) {
                        data.links[i].linkindex = data.links[i - 1].linkindex + 1;
                    }
                    else {
                        data.links[i].linkindex = 1;
                    }
                    // save the total number of links between two nodes
                    if (mLinkNum[data.links[i].target + "," + data.links[i].source] !== undefined) {
                        mLinkNum[data.links[i].target + "," + data.links[i].source] = data.links[i].linkindex;
                    }
                    else {
                        mLinkNum[data.links[i].source + "," + data.links[i].target] = data.links[i].linkindex;
                    }
                }
            }
        }

</script>

最佳答案

基本上,强制布局是根据索引而不是 id 或名称来工作的。所以你必须明确说明你想在你的情况下通过 id 链接:

var edges = [];
data.links.forEach(function(e) {
    var sourceNode = data.nodes.filter(function(n) {
        return n.id === e.source;
    })[0],
        targetNode = data.nodes.filter(function(n) {
            return n.id === e.target;
        })[0];

    edges.push({
        source: sourceNode,
        target: targetNode
    });
});

上面的代码检查哪个节点与链接 Source 具有相同的 id,然后将其插入 Edges 数组的源中,并且对于目标也相同。然后使用此边数组创建图形:

力量:

force
      .nodes(data.nodes)
      .links(edges)

对于链接:

var link = svg.selectAll(".link")
          .data(edges)

这是我用您的 new_json 实现的 fiddle :https://jsfiddle.net/thatOneGuy/60oLwg8t/1/

或者在这里:

 
  var data = 
      {
        "nodes": [{
          "id": 124587,
          "name": "paper1",
          "citation": 5,
          "group": 1
        }, {
          "id": 178456,
          "name": "paper2",
          "citation": 8,
          "group": 2
        }],
        "links": [{
          "source": 124587,
          "target": 178456,
          "name": "A-B-1",
          "value": 8
        }]
      };

console.log(data.nodes)
console.log(data.links)
      var width = 960,
        height = 500;

      var color = d3.scale.category20();

      var force = d3.layout.force()
        .charge(-120)
        .linkDistance(30)
        .size([width, height]);

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

      var edges = [];
data.links.forEach(function(e) {
    var sourceNode = data.nodes.filter(function(n) {
        return n.id === e.source;
    })[0],
        targetNode = data.nodes.filter(function(n) {
            return n.id === e.target;
        })[0];

    edges.push({
        source: sourceNode,
        target: targetNode,
        value: e.Value
    });
});


        force
          .nodes(data.nodes)
          .links(edges)
          .start();
        var link = svg.selectAll(".link")
          .data(edges)
          .enter().append("line")
          .attr("class", "link")
          .style("stroke-width", 2);

        var node = svg.selectAll(".node")
          .data(data.nodes)
          .enter().append("circle")
          .attr("class", "node")
          .attr("r", 5)
          .style("fill", 'red')
          .call(force.drag);

        node.append("title")
          .text(function(d) {
            return d.name;
          });

        force.on("tick", function() {
          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;
            });
        }); 
.node {
  stroke: #fff;
  stroke-width: 1.5px;
}

.link {
  stroke: #999;
  stroke-opacity: .6;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

关于javascript - 如何根据d3.js图形库中的节点id连接边与节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37031299/

相关文章:

Java:解析一个字符串中的多个Json对象

ruby-on-rails - 将静态 JSON 数据导出到 Amazon S3 并通过 AJAX 检索它

javascript - 我怎样才能从 d3js 中折叠的所有节点开始?

javascript - 如何将类应用(和更改)到已存在的 SVG 元素

javascript - 数据绑定(bind)到文本区域和 ng-show 问题

javascript - 数组中的自定义全局过滤器

javascript - Lodash - 在具有默认值的路径处获取值

json - 具有枚举键的 Map 的 GSON 自定义序列化器

javascript - 使用模板以表格格式显示数据

javascript - D3.js - 格式化数字 - 引发错误