【问题标题】:Right to Left Icicle Tree从右到左的冰柱树
【发布时间】:2021-09-09 23:17:26
【问题描述】:

如何镜像 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;
      }
  }

但它不起作用。

【问题讨论】:

    标签: javascript html d3.js tree


    【解决方案1】:

    这是example

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

    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);
    }
    

    【讨论】:

    • 如果我想转换成垂直,点击会发生什么?我知道转换为.attr("transform", d => "translate(" + d.target.x0 + "," + d.target.y0 + ")");,但使用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 我能做什么?
    猜你喜欢
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多