0

I am currently working on adding text above the links in my visualization and would like to position it at the end of the link, just before the target node.

And this is my code of adding text to the link

// Add the link text
var linkText = svg.append("g").selectAll(".link")
                .data(graph.links)
                .enter()
                .append("text").attr('class','linkText')
                .attr("x", function(d) {return d.target.x - 110; })
                .attr("y", function(d) { return d.source.y + (d.target.y - d.source.y) / 2; })
                .attr("dy", ".35em")
                .attr("text-anchor", "end")
                .attr("transform", null)
                .text(function(d) { return "Total : " + d.value + " $"; })
                .attr("text-anchor", "start")

And this is my full code https://jsfiddle.net/kaowlx/c5z2sy1n/1/

I have managed to add text and position it along the x-axis, but I am still facing a challenge with the y-axis. Despite adjusting several values, I am unable to position it correctly on the chart.
This is current result. enter image description here

And the result that I want is something like this

enter image description here

So are there anyway that I can position the text on the link. Thank you.

Kaow
  • 483
  • 2
  • 9
  • 22

1 Answers1

0

Use d.target instead of d.source to position it vertically based on target:

var linkText = svg.append("g").selectAll(".link")
                    .data(graph.links)
                    .enter()
                    .append("text").attr('class','linkText')
                    .attr("x", function(d) {return d.target.x - 80; })
                    .attr("y", function(d) { return d.target.y - 10; }) // The fix
                    .attr("dy", ".35em")
                    .attr("text-anchor", "end")
                    .attr("transform", null)
                    .text(function(d) { return "Total : " + d.value + " $"; })
                    .attr("text-anchor", "start")

Here is a fiddle: https://jsfiddle.net/jqc3awsd/5/

M.A Shahbazi
  • 876
  • 9
  • 23
  • Thank you very much. But after adding more source nodes, I encountered another issue where the text is positioned in the same place as the first one. Is there any way to make each text stay with its respective link? Here is a fiddle : https://jsfiddle.net/kaowlx/8mxd9woh/1/ – Kaow Apr 05 '23 at 08:55