问题描述
我对 d3.js(以及一般的 SVG)非常陌生,我想做一些简单的事情:带有角度连接器的树/树状图.
I'm very new to d3.js (and SVG in general), and I want to do something simple: a tree/dendrogram with angled connectors.
我已经从这里蚕食了 d3 示例:http://mbostock.github.com/d3/ex/cluster.html我想让它更像这里的 protovis 示例:
I have cannibalised the d3 example from here:http://mbostock.github.com/d3/ex/cluster.htmland I want to make it more like the protovis examples here:
- http://mbostock.github.com/protovis/ex/indent.html
- http://mbostock.github.com/protovis/ex/dendrogram.html
我从这里开始:http://jsbin.com/ugacud/2/edit#javascript,html,我认为这是错误的以下片段:
I have made a start here: http://jsbin.com/ugacud/2/edit#javascript,html and I think it's the following snippet that's wrong:
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.y, d.x]; });
但是没有明显的替代品,我可以使用d3.svg.line
,但我不知道如何正确集成它,理想情况下我想要一个弯头连接器....虽然我想知道我是否为此使用了错误的库,因为我看到的许多 d3 示例都使用重力来绘制物体而不是树木的图形.
However there's no obvious replacement, I could use d3.svg.line
, but I don't know how to integrate it properly, and ideally I'd like an elbow connector....although I am wondering if I am using the wrong library for this, as a lot of the d3 examples I've seen are using the gravitational force to do graphs of objects instead of trees.
推荐答案
用自定义路径生成器替换 diagonal
函数,使用 SVG 的H"和V"路径命令.
Replace the diagonal
function with a custom path generator, using SVG's "H" and "V" path commands.
function elbow(d, i) {
return "M" + d.source.y + "," + d.source.x
+ "V" + d.target.x + "H" + d.target.y;
}
请注意,源和目标的坐标(x 和 y)交换了.此示例以水平方向显示布局,但布局始终使用相同的坐标系:x 是树的宽度,y 是树的深度.因此,如果您想显示右边缘具有叶子(最底部)节点的树,则需要交换 x 和 y.这就是对角线的投影函数所做的,但在上面的肘部实现中,我只是硬编码了行为,而不是使用 可配置功能.
Note that the source and target's coordinates (x and y) are swapped. This example displays the layout with a horizontal orientation, however the layout always uses the same coordinate system: x is the breadth of the tree, and y is the depth of the tree. So, if you want to display the tree with the leaf (bottommost) nodes on the right edge, then you need to swap x and y. That's what the diagonal's projection function does, but in the above elbow implementation I just hard-coded the behavior rather than using a configurable function.
如:
svg.selectAll("path.link")
.data(cluster.links(nodes))
.enter().append("path")
.attr("class", "link")
.attr("d", elbow);
还有一个工作示例:
这篇关于d3 中带有弯头连接器的树/树状图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!