按照 mbostock 给出的示例,使用 csv 创建力图:
How to convert to D3's JSON format?
我正在使用 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);
或在勾选功能中进一步向下:
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", function(d) {return d[7];});
可能有以下几个原因导致了问题: 1. 我似乎没有一个很好的 links 函数或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
最佳答案
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);
关于graph - 使用 CSV 属性设置链接长度、节点大小 d3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13335225/