Tree D3.js with an odd number of vertices, no edges shown

I have the following JavaScript code that uses the D3.js library to draw a tree (it follows the standard structure that can be found in 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(" + dx + "," + dy + ")"; }); 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

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

+1
source share
1 answer

You are missing the style for node links. Something has changed:

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

Or, install it on the link itself:

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

It depends on the odd and even number, because by default the path has no prime and the color is black. So the straight line does not appear, but the curved ones fill up.

+3
source

Source: https://habr.com/ru/post/956577/


All Articles