Reputation: 3267
I want to add the id
to the nodes of the graph in the example of
https://d3-graph-gallery.com/graph/network_basic.html
I tried
...
node.append("text")
.attr("dx", 12)
.attr("dy", ".35em")
.text(function(d) { return d.name });
...
but the name does not appear
how can I add the name next to the node
Upvotes: 0
Views: 354
Reputation: 346
The node
variable represents a selection of SVG circles, which cannot contain text elements. You have to use a group element as a parent to hold the circle and the text elements.
First create a selection of group elements that the force simulation will place:
const nodes = svg
.selectAll("g")
.data(data.nodes)
.join("g");
Then add your circle and your text in the groups:
nodes.append("circle")
.attr("r", 20)
.style("fill", "#69b3a2")
nodes.append("text")
.attr("text-anchor", "middle") // text is centered in the circle
.attr("alignment-baseline", "middle")
.text(d => d.name);
Because the force simulation works on group elements, the ticked()
function must be adapted to translate them:
nodes.attr("transform", d => `translate(${d.x+6},${d.y-6})`);
See example here: https://codepen.io/ccasenove/pen/eYKzmwd
Upvotes: 1