我testinf d3.js
,我试图添加一个根节点(JsFiddle的中心之一)和子节点之间的链接。我怎么能做到这一点?添加链接到我的节点与d3.js
这里是我到目前为止的代码: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/ 我现在唯一需要的是直线,而不是弯曲的。任何人 ?
创建“节点”,然后生成具有节点类元素。您必须对“链接”执行相同的操作:使用源和目标的坐标创建svg:line元素。 – Matthieu
感谢@Matthieu,我意识到这一点,并理解一般原则,但我没有用d3 js编写实际的代码并使其工作(我已经从几个例子中已经尝试过)不够舒适; –
也许你可以直接使用强制布局:https://github.com/mbostock/d3/wiki/Force-Layout或者看看d3js svg行功能 – Matthieu