首页 > 解决方案 > 从右到左的冰柱树

问题描述

如何镜像 d3 树?我已经使用了这些代码https://observablehq.com/@d3/zoomable-icicle但我不能把父亲放在正确的位置。我认为是attr("transform", d => translate(${d.y0},${d.x0}))和我尝试过的功能

positions(d){
      console.log(d.depth)
      if (d.depth == 0){
          d = d.children[0].children[0].children[0];
          return (d.x0);
      }
      else if(d.depth == 1){
          d = d.children[0];
          return (d.x0);
      }
      else if(d.depth == 2){
          d = d.parent;
          return (d.x0);
      }
      else{
        return 0;
      }
  }

但它不起作用。

标签: javascripthtmld3.jstree

解决方案


这是一个例子

我们可以定义一个函数来获取镜像的水平位置:

function getFlippedPosition(d) {
  return width - ((d.depth + 1) * (d.y1 - d.y0));
}

然后创建组变成

  const cell = svg
    .selectAll("g")
    .data(root.descendants())
    .join("g")
      .attr("transform", d => `translate(${getFlippedPosition(d)},${d.x0})`)

类似地,clicked函数可以更新如下:

function clicked(event, p) {
  focus = focus === p ? p = p.parent : p;

  root.each(d => d.target = {
    x0: (d.x0 - p.x0) / (p.x1 - p.x0) * height,
    x1: (d.x1 - p.x0) / (p.x1 - p.x0) * height,
    y0: d.y0 - p.y0,
    y1: d.y1 - p.y0,
    // this line is new:
    depth: d.depth - p.depth,
  });

  const t = cell.transition().duration(750)
      // this line is updated:
      .attr("transform", d => `translate(${getFlippedPosition(d.target)},${d.target.x0})`)

  rect.transition(t).attr("height", d => rectHeight(d.target));
  text.transition(t).attr("fill-opacity", d => +labelVisible(d.target));
  tspan.transition(t).attr("fill-opacity", d => labelVisible(d.target) * 0.7);
}

推荐阅读