D3: Substituting d3.svg.diagonal() with d3.svg.line()

杀马特。学长 韩版系。学妹 提交于 2019-11-28 06:55:28

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; });

function lineData(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}
    ];
    return line(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

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"); 
mobeets

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

Note that changing line to diagonal will make it work.

Just set the d attribute of link to line:

.attr("d", line)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!