I am just starting to learn D3 and currently working through understanding this example.
I am trying to get text to display next to each node in the graph. In the JSON data, there is a key named name
, which contains the name of a character from Les Misérables. I am trying to display this text next to each node using this code:
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 5)
.style("fill", "black")
.text(function(d) { return d.name;}).style("font-family", "Arial").style("font-size", 12)
.call(force.drag);
I've basically just altered the .text
to try and display text. Can anyone explain how I can get text to display? Thanks in advance.
Last Updated : 23 Aug, 2020 The selection.text () function in d3.js is used to set the text content to the specified value of the selected elements thus, it replaces any existing child elements. If the value that is given is constant than all elements will be given that constant value.
Here, the text ‘d3.js’ is given a class name of d3js and the text ‘d3noob.org’ is given a class name of d3noob. So the ‘d3.js’ text is selected using text.d3js and ‘d3noob.org’ is selected using text.d3noob.
Let‘s look first at the mouseover: on ('mouseover', function (d) { d3. select ('#tooltip'). style ('opacity', 1). text (d) }) We‘re showing the tooltip element and setting the text to be the text of the data element that we‘re hovering over. In our example, if we hover over the first element the tooltip would have a as its text.
Easily the most basic method for displaying data that is part of a d3.js visualization when mousing over part of the graphic is to use the title tag.
The SVG <circle>
element will not display any text that you place inside it using the .text
function. A way to display the text would be to make the nodes of the graph SVG <g>
elements. These can then contain a <circle>
and a <text>
child elements.
This could look like this :
\\create graph nodes using groups
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("g").call(force.drag);
node.append("circle")
.attr("class", "node")
.attr("r", 5)
.style("fill", function (d) { return color(d.group); });
node.append("text")
.text(function (d) { return d.name; });
You would also need to change the force so that it transforms the group <g>
on a tick.
force.on("tick", function () {
...
node.attr("transform", function (d) { return "translate(" + d.x + "," + d.y + ")"; });
});
You can see it in action for a small graph at http://jsfiddle.net/vrWDc/19/. This method may not be very efficient when applied to a large graph due to the amount of text that needs to be rendered.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With