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

后端 未结 4 949
离开以前
离开以前 2020-12-08 16:04

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 t

4条回答
  •  我在风中等你
    2020-12-08 16:22

    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

提交回复
热议问题