I’m using d3.force to setup nodes and have links connecting each of the nodes. It all works great when I’m using circles as the nodes:
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);
However, if I change the nodes to use “g”, it stops working:
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);
I can see the circles being added to the g elements but they’re not where they’re supposed to be and they are not connected by the links.
I’d really like to use “g” elements as the nodes so that I can add text to it. Does anyone have any insight to this?
Alternatively, if there’s a way to add text to a “circle” element. I’m also open to that.
Thanks!
Try consolidating this into one statement, with the call at the end:
Then you can attach other elements, such as text.