使用CSV属性设置链接长度,节点大小为d3

时间:2012-11-11 20:39:57

标签: graph d3.js directed-graph

按照mbostock给出的示例创建一个带有csv的力图:

How to convert to D3's JSON format?

http://bl.ocks.org/2949937

我正在使用D3创建一个力图,但我不确定如何/在何处调用CSV行中的值来设置节点大小,颜色或链接长度。

我尝试了一些事情,例如:

links.forEach(function(link) {
    link.source = nodeByName(link.user1);
    link.target = nodeByName(link.user2);
    link.size = nodeByName(link.somevaluefromcsv)
    link.distance = nodeByName(link.somevaluefromcsv);
  });

这是错的。据我所知,它只是生成空节点,并且值无法在其他地方调用。

var node = svg.selectAll(".node")
      .data(nodes)
    .enter().append("circle")
      .attr("class", "node")
      .attr("r", function(d) {return d[3];}) //this is not returing any value as far as I can tell.
      .call(force.drag);

或在tick函数中向下:

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

可能有一些问题导致: 1.我似乎没有一个很好的链接函数或nodesbyName数组或函数的概念模型。

CSV中的典型行(现在),顺序如下: 时间,用户1,用户2,相似度得分,总积分,积分,积分,长度 是:

1223.8167,john6,john5,0.153846153846,1,0,1,5
1223.9166,john6,john5,0.185185185185,8,0,8,6
1223.9667,bobby4,bobby3,0.402777777778,224,320,-96,15
1224.1167,bobby4,bobby3,0.402777777778,226,310,-84,15
1224.2,bobby4,bobby3,0.402777777778,240,283,-43,15
1224.2,john6,john5,0.185185185185,2,0,2,5
1224.2,john6,john5,0.153846153846,2,0,2,5
1224.2667,bobby4,bobby3,0.397058823529,0,24,-24,13
1224.2833,john6,john5,0.153846153846,1,0,1,5
1224.45,bobby4,bobby3,0.397058823529,0,21,-21,13
1224.55,bobby4,bobby3,0.442857142857,0,18,-18,14

1 个答案:

答案 0 :(得分:3)

function nodeByName(name) - 创建新节点或返回名称指定为参数的现有节点。 如果您需要从链接传递节点属性,可以在forEach

中执行
links.forEach(function(link) {
    link.source = nodeByName(link.user1);
    link.target = nodeByName(link.user2);
    link.source.radius = link.radius
    link.size = link.somevaluefromcsv;
    link.distance = link.somevaluefromcsv;
});

links - 节点之间的链接数组。

var node = svg.selectAll(".node")
      .data(nodes)
    .enter().append("circle")
      .attr("class", "node")
      .attr("r", function(d) {return d.radius;}) // radius property of node
      .call(force.drag);