D3.js树具有奇数个顶点,边没有显示 [英] D3.js tree with odd number of vertices, edges not shown

查看:192
本文介绍了D3.js树具有奇数个顶点,边没有显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下JavaScript代码,使用 D3.js 库绘制树(它遵循标准结构可以在各种在线教程中找到):

I have the following JavaScript code that uses the D3.js library to draw a tree (it follows the standard structure one can find in the various online tutorials):

var json = {
    "name": "A",
        "children": [{
        "name": "B"
    }]
};

var tree = d3.layout.tree().size([200, 200]);

var nodes = tree.nodes(json);

var vis = d3.select("#chart").attr("width", 300)
    .attr("height", 300)
    .append("svg:g")
    .attr("transform", "translate(40, 40)");

var diagonal = d3.svg.diagonal();

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

var node = vis.selectAll("g.node").data(nodes).enter().append("svg:g")
    .attr("class", "node")
    .attr("transform", function (d) {
    return "translate(" + d.x + "," + d.y + ")";
});

node.append("svg:circle").attr("r", 10);

node.append("svg:text").attr("dx", function (d) {
    return 10;
})
    .attr("dy", 10)
    .attr("text-anchor", function (d) {
    return "start";
})
    .text(function (d) {
    return d.name;
});

JSFIDDLE

JSFIDDLE

它的工作原理很好,除了一个顶点有奇数个孩子的树,...);在这种情况下,将不绘制奇数顶点的边缘(例如,在上述示例中,不显示A和B之间的边缘)。我缺少什么?

It works mostly fine, except for trees in which a vertex has an odd number of children (1, 3, ...); in this case, the edge for the odd vertex will not be drawn (e.g., in the above example, the edge between A and B is not displayed). What am I missing?

推荐答案

您缺少节点链接的样式。此处的变化:

You are missing the style for the node links. Something variation of this:

<style>
.link {
    fill: none;
    stroke: #ccc;
    stroke-width: 4.5px;
}
</style>

或者,在链接本身设置:

Or, set it on the link itself:

.attr("d", diagonal).attr({ 'fill': 'none', 'stroke': 'grey', 'stroke-width': 4 });

这取决于奇数对偶数,因为默认情况下路径没有笔画,黑色。所以直线不显示,但弯曲的填充。

It depends on odd vs. even number because by default a path gets no stroke and a fill color of black. So a straight line doesn't show up but the curved ones get filled.

这篇关于D3.js树具有奇数个顶点,边没有显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆