如何使用D3对角线功能绘制曲线?

问题描述 投票:19回答:2

我看了样本http://bl.ocks.org/mbostock/raw/4063570/

它从源到目标从左到右生成很好的合并线。

在我的情况下,我需要手动布局节点并放置x,y坐标。在这种情况下,线路不会在源节点处合并。以下是重现此问题的测试代码:

var data = [ {name: "p1", children: [{name: "c1"}, {name: "c2"}, {name: "c3"}, {name: "c4"}]}];
var width = 400, height = 200, radius = 10, gap = 50;

// test layout
var nodes = [];
var links = [];
data.forEach(function(d, i) {
    d.x = width/4;
    d.y = height/2;
    nodes.push(d);
    d.children.forEach(function(c, i) {
        c.x = 3*width/4;
        c.y = gap * (i +1) -2*radius;
        nodes.push(c);
        links.push({source: d, target: c});
    })
})

var color = d3.scale.category20();

var svg = d3.select("#chart").append("svg")
        .attr("width", width)
        .attr("height", height)
        .append("g");
var diagonal = d3.svg.diagonal()
        .projection(function(d) { return [d.x, d.y]; });

var link = svg.selectAll(".link")
        .data(links)
        .enter().append("path")
        .attr("class", "link")
        .attr("d", diagonal);

var circle = svg.selectAll(".circle")
        .data(nodes)
        .enter()
        .append("g")
        .attr("class", "circle");

var el = circle.append("circle")
        .attr("cx", function(d) {return d.x})
        .attr("cy", function(d) {return d.y})
        .attr("r", radius)
        .style("fill", function(d) {return color(d.name)})
        .append("title").text(function(d) {return d.name});

http://jsfiddle.net/zmagdum/qsEbd/有这样的样本:

但是,看起来曲线靠近节点的行为与所需的相反。我希望它们在节点处水平直线开始,并在中间形成一条曲线。有这个诀窍吗?

javascript svg d3.js curve
2个回答
26
投票

这个解决方案基于优秀的@bmdhacks解决方案,但是,我相信我的稍微好一点,因为它不需要在数据本身内交换xy

想法是你可以使用diagonal.source()diagonal.target()来交换xy

var diagonal = d3.svg.diagonal()
    .source(function(d) { return {"x":d.source.y, "y":d.source.x}; })            
    .target(function(d) { return {"x":d.target.y, "y":d.target.x}; })
    .projection(function(d) { return [d.y, d.x]; });

所有x y交换现在都封装在上面的代码中。

结果:

这里也是jsfiddle


8
投票

请注意,在块示例中,x和y值在链接中交换。这通常会将链接绘制在错误的位置,但他还提供了一个投影功能,可以将它们交换回来。

var diagonal = d3.svg.diagonal()
    .projection(function(d) { return [d.y, d.x]; });

这是你应用这种技术的jsfiddle:http://jsfiddle.net/bmdhacks/qsEbd/5/

© www.soinside.com 2019 - 2024. All rights reserved.