我使用 d3.force 来设置节点并具有连接每个节点的链接。当我使用圆圈作为节点时,一切都非常有效:
var nodes = [{ title: "ABC", group: 1 }, { title: "DEF", group: 1 }, { title: "Blah", group: 1 }];
var links = [{ source: 0, target: 1 }, { source: 0, target: 2 }];
var force = d3.layout.force()
.charge(-120)
.linkDistance(function(d) {
console.log(d);
return 250 * Math.random() + 100;
})
.size([r, r]);
force.links(links)
.nodes(nodes)
.start();
var link = svg.selectAll("line.link")
.data(links)
.enter()
.append("line")
.attr("class", "link")
.style("stroke-width", 1);
var node = svg.selectAll("circle.node")
.data(nodes)
.enter()
.append("circle")
.attr("class", "node")
.attr("r", 15)
.call(force.drag);
但是,如果我将节点更改为使用“g”,它就会停止工作:
var node = svg.selectAll("g.node")
.data(nodes)
.enter()
.append("g")
.attr("class", "node")
.attr("r", 15)
.call(force.drag);
var circle = node.append("circle")
.attr("fill", function(d) {
var b = Math.floor(255 * Math.random()),
rgba = "rgba(0, 0, " + b + ", 0.7)";
return rgba;
})
.attr("r", 15);
我可以看到圆圈被添加到 g 元素中,但它们不在应有的位置,并且它们没有通过链接连接。
我真的很想使用“g”元素作为节点,以便我可以向其添加文本。有人对此有任何见解吗?
或者,如果有办法将文本添加到“圆形”元素。我对此也持开放态度。
谢谢!
最佳答案
尝试将其合并到一个语句中,并在末尾调用:
var node = svg.selectAll("g.node")
.data(nodes)
.enter()
.append("g")
.attr("class", "node")
.append("circle")
.attr("fill", function(d) {
var b = Math.floor(255 * Math.random()),
rgba = "rgba(0, 0, " + b + ", 0.7)";
return rgba;
})
.attr("r", 15)
.call(force.drag);
然后您可以附加其他元素,例如文本。
关于javascript - d3.js:强制布局仅适用于圆形吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13280847/