Skip to content Skip to sidebar Skip to footer

D3: Substituting D3.svg.diagonal() With D3.svg.line()

I have implemented the following graph with the edges rendered with d3.svg.diagonal(). However, when I try substituting the diagonal with d3.svg.line(), it doesn't appear to pull t

Solution 1:

Question is quite dated, but since I don't see an answer and someone might face the same problem, here it is.

The reason why simple replacement of diagonal with line is not working is because d3.svg.line and d3.svg.diagonal return different results:

  • d3.svg.diagonal returns function that accepts datum and its index and transforms it to path using projection. In other words diagonal.projection determines how the function will get points' coordinates from supplied datum.
  • d3.svg.line returns function that accepts an array of points of the line and transforms it to path. Methods line.x and line.y determine how coordinates of the point retreived from the single element of supplied array

D3 SVG-Shapes reference

SVG Paths and D3.js

So you can not use result of the d3.svg.line directly in d3 selections (at least when you want to draw multiple lines).

You need to wrap it in another function like this:

var line = d3.svg.line()
                 .x( function(point) { return point.lx; })
                 .y( function(point) { return point.ly; });

functionlineData(d){
    // i'm assuming here that supplied datum // is a link between 'source' and 'target'var points = [
        {lx: d.source.x, ly: d.source.y},
        {lx: d.target.x, ly: d.target.y}
    ];
    returnline(points);
}

// usage:var link= svg.selectAll("path")
    .data(links)
    .enter().append("path")
    .attr("d",lineData)
    .attr("class", ".link")
    .attr("stroke", "black")
    .attr("stroke-width", "2px")
    .attr("shape-rendering", "auto")
    .attr("fill", "none");   

Here's working version of jsFiddle mobeets posted: jsFiddle

Solution 2:

I had the same problem...There's a jsFiddle here.

Note that changing line to diagonal will make it work.

Solution 3:

Perhaps encapsulating the diagonal function and editing its parameters could work for you:

var diagonal = d3.svg.diagonal();
var new_diagonal = function (obj, a, b) {
    //Here you may change the reference a bit.var nobj = {
        source : {
            x: obj.source.x,
            y: obj.source.y
        },
        target : {
            x: obj.target.x,
            y: obj.target.y
        }
    }
    return diagonal.apply(this, [nobj, a, b]);
}
var link= svg.selectAll("path")
    .data(links)
    .enter().append("path")
    .attr("d",new_diagonal)
    .attr("class", ".link")
    .attr("stroke", "black")
    .attr("stroke-width", "2px")
    .attr("shape-rendering", "auto")
    .attr("fill", "none"); 

Solution 4:

Just set the d attribute of link to line:

.attr("d", line)

Post a Comment for "D3: Substituting D3.svg.diagonal() With D3.svg.line()"