使用d3.js

时间:2015-05-18 12:29:14

标签: d3.js

我是testinf d3.js,我正在尝试在根节点(JsFiddle中的中心节点)和子节点之间添加链接。我怎样才能做到这一点?

以下是我目前的代码:http://jsfiddle.net/fLqekg12/2/

var container = d3.select("svg#svg");
var data = [2, 1, 1, 1, 1, 1, 1];

var dataTree = {
    id: "root",
    size: 12,
    children: data.map(function (d) {
        return {
            size: 10,
            parent: "root"
        };
    })
};

var maxRadius = 50,
    padding = 40;

var radiusScale = d3.scale.sqrt()
    .domain([0, 50 /* d3.max(data) */ ])
    .range([0, 50]); // maxRadius

var roughCircumference = d3.sum(data.map(radiusScale)) * 2 + padding * (data.length - 1),
    radius = roughCircumference / (Math.PI * 2);

// make a radial tree layouts
var tree = d3.layout.tree()
    .size([360, radius])
    .separation(function (a, b) {
    return radiusScale(a.size) + radiusScale(b.size);
});

// create a holder group for all the graph nodes
var svgGroup = container.append('g')
    .attr('transform', 'translate(' + 80 + ',' + 90 + ')');


var nodes = tree.nodes(dataTree),
    links = tree.links(nodes); // and then... ?

// declare the nodes (this creates placed groups)
var svgNodes = svgGroup.selectAll('.node')
    .data(nodes) // cut out the root node, we don't need it : nodes.slice(1)
.enter().append('g')
    .attr('class', 'node')
    .attr('transform', function (d) {
    return "rotate(" + (d.x - 90) + ") translate(" + d.y + ")";
});

// append a cirl to all nodes groups
svgNodes.append('circle').attr('r', function (d) {
    return d.size;
});

修改

使用此代码取得了进展。

var diagonal = d3.svg.diagonal.radial()
        .projection(function (d) {
        return [d.y, d.x / 180 * Math.PI];
    });

var svgLinks = svgGroup.selectAll('path')
        .data(tree.links(nodes))
        .enter().append('svg:path')
        .attr('class', 'link')
        .attr('d', diagonal)
        .attr("fill", "none")
        .attr("stroke", "gray");

小提琴更新:http://jsfiddle.net/fLqekg12/4/ 我现在唯一需要的是直线而不是曲线。任何人?

2 个答案:

答案 0 :(得分:0)

计算并创建节点后,您必须将链接创建为svg line元素: var link = svgGroup.selectAll('line.link')     。数据(链接)     。。进入()追加( 'SVG:线')         .attr(“class”,“link”)         .attr( “风格”, “行程:黑”)         .attr(“x1”,function(d){return ...(x坐标源节点)})         .attr(“y1”,function(d){return ...(y坐标源节点)})         .attr(“x2”,function(d){return ...(x坐标目标节点)})         .attr(“y2”,function(d){return ...(y坐标目标节点)}); 你必须找到从x,y极坐标计算位置的好公式。

答案 1 :(得分:0)

两种有效的解决方案是:

使用路径(最简单的路径,但无法将曲线转换为直线):http://jsfiddle.net/fLqekg12/4/

使用行。诀窍是线不能直接用于代替路径(see why here),如果你转换节点,它就不起作用。

我找到的解决方案是found from this post:如果您的节点被转换,那么必须转换行:

d.target.x / 180 * Math.PI)y1上使用y2,因为我想要一个径向投影,最后再用以下方式转换线条:

svgLinks.attr("transform", function (d) {
        return "rotate(" + (d.target.x - 90) + ")";
});

这里有完整的工作示例: http://jsfiddle.net/fLqekg12/6/

相关问题