D3.js D3V4(树形图)-动态计算给定动态节点数的SVG的高度

D3.js D3V4(树形图)-动态计算给定动态节点数的SVG的高度,d3.js,svg,D3.js,Svg,我动态地更改树形图的数据,不知道SVG的高度应该是多少。如何计算树形图的高度以更新SVG维度 小提琴示例: 请查看上的代码,因此要求我发布一些带有fiddle链接的代码: var treemap = d3.tree().nodeSize([40, 40]); root = d3.hierarchy(data, function(d) { return d.children; }); root.x0 = 100; root.y0 = 0; function update(source) {

我动态地更改树形图的数据,不知道SVG的高度应该是多少。如何计算树形图的高度以更新SVG维度

小提琴示例:

请查看上的代码,因此要求我发布一些带有fiddle链接的代码:

var treemap = d3.tree().nodeSize([40, 40]);

root = d3.hierarchy(data, function(d) { return d.children; });
root.x0 = 100;
root.y0 = 0;
function update(source) {

  // Assigns the x and y position for the nodes
  var data = treemap(root);

  // Compute the new tree layout.
  var nodes = data.descendants(),
      links = data.descendants().slice(1);

  // Normalize for fixed-depth.
  let connectorLength = 200; // the length of the lines in pixels
  nodes.forEach(function(d){ d.y = d.depth * connectorLength});

nodes = nodes.filter(function(d){
return d.depth != 0;
})
...

由于您指定
节点大小为
[40,40]
且您有129个节点,因此高度应为:

var height = 40 * 129;
var height = treemap.nodeSize()[1] * nodes.length;
由于您希望动态计算它,它应该是:

var height = 40 * 129;
var height = treemap.nodeSize()[1] * nodes.length;
另外,当指定
tree.nodeSize
时,根节点将位于
0,0
。因此,您必须翻译主组:

.attr("transform", "translate("+ margin.left + "," + (height/2) + ")");
以下是更新的小提琴: