首页 > 解决方案 > D3.js 寻找隐藏选择性分层元素的有效方法

问题描述

我有一个旭日形图,我想显示与所选元素相关的所有元素(上升和后代)。我希望未过滤元素的比例保持不变(基本上不透明度设置为 0)。

例如,如果我只想显示苹果元素,则被划掉的元素会消失,但苹果及其所有(后代和后代)仍将存在。

旭日形首饰显示移除的元素

这是一个输出旭日形(未过滤)的 MWE https://jsfiddle.net/pcristini/d7ot253c/70/。除了我定义的函数之外,我不确定如何处理这个arcVisible问题,我只是不知道最好的方法。

此外,任何与我如何在代码中执行其他任何操作相关的反馈都将不胜感激。我以前对 D3 做的不多,而且我的 JS 技能也很差。

标签: javascriptd3.js

解决方案


所以我不知道这是否是一种超级有效的方法,但这就是我想出的。

所以首先我首先找到指定级别的最大值

function findMax(data, level) {
  var max;
  var orgs = {};
  
  // Loop over each data element
  data.each(d => {
    // if it's at the specified depth
    if (d.depth == level)
    {
      // If it's not already in the orgs structure (counting the maxs), add it
      if (!(d.data.name in orgs))
      {
        orgs[d.data.name] = 0;
      }
      // Increase the total of this value
      orgs[d.data.name] += d.value;
    }
  });
  // Find the element with the maximum value
  max = Object.entries(orgs).reduce((a, e) => e[1] > a[1] ? e : a);

  // Just return the name
  return max[0];
}

现在我们可以找到所选最大值的所有祖先和后代

function maxTrees(data, name){
  var max_el = [];
  
  data.each(d => {
    if (d.data.name == name)
      // Put all the ancestors and descendants into an array
      max_el = max_el.concat(d.ancestors().reverse().slice(1), d.descendants().slice(1));
  });
  
  return max_el;  
}

现在,当我们显示可见元素时,我们会查找当前切片是否是可见列表的一部分:

function arcVisible(d) {
  return max_elements.indexOf(d) >= 0;
}


path.attr("fill-opacity", d => arcVisible(d) ? 0.6 : 0.0);

我已经用解决方案更新了小提琴。我实际上是在寻找最大计数(不像我在上面的 MWE 中问的......我很抱歉)


推荐阅读