1

I need to convert a forceDirected layout to use stepped path curves instead of point to point straight lines. Typical links connecting nodes use this method.

  function ticked() {
   link
    .attr("x1", function(d) { return d.source.x; })
    .attr("y1", function(d) { return d.source.y; })
    .attr("x2", function(d) { return d.target.x; })
    .attr("y2", function(d) { return d.target.y; });

node
     .attr("cx", function (d) { return d.x+6; })
     .attr("cy", function(d) { return d.y-6; });

}

Here is an example of a forceDirected as a use case

https://www.d3-graph-gallery.com/graph/network_basic.html

Here a rough idea of how I want the links to be rendered shown in red.

enter image description here

Here is a method I am trying to use as a solution

https://www.geeksforgeeks.org/d3-js-curvestep-method/

and here is a snippet of code I am testing based on the linked example above without much success

var line = d3.line()
.x((d) => d.x)
.y((d) => d.y)
.curve(d3.curveStep);

 function addConnections(o){
  // o  is link.d from existing links between nodes

 var ldata = []

 var d = {x: o.source.x,y:o.source.y}
 ldata.push(d)
 var d = {x: o.target.x,y:o.target.y}
 ldata.push(d)

 var steps = svg
.selectAll("path")
.data(ldata)
.enter()
.append("path")
.attr("d",function(d){
console.log(d)
line(d)
})
.classed("steps",true)
}
alQemist
  • 362
  • 4
  • 13
  • 1
    Take a look at the third snippet in this [answer](https://stackoverflow.com/a/55444414/7106086) which uses a (custom) curve for a d3 force layout. To use a curveStep, you just need to replace `.curve(curve)` with `.curve(d3.curveStep)` to get the desired result. – Andrew Reid Dec 03 '20 at 16:37
  • Thanks for your answer Andrew - I was able to get the results I was looking for. I am posting as an answer but looking for suggestions on refactoring the code to make it more eloquent – alQemist Dec 03 '20 at 16:42

1 Answers1

0

enter image description here

Here is the final simple solution I came up with that works for generating stepped curves as links between nodes in forceDirected layout

line = d3.line()
.x((d) => d.x)
.y((d) => d.y + 5)
.curve(d3.curveStepAfter)

function ticked(){

link
.attr("d", function (d) {
a.push({x: d.source.x, y: d.source.y});
a.push({x: d.target.x, y: d.target.y});
return line(a)
})

}

alQemist
  • 362
  • 4
  • 13