【问题标题】:How to access elements from dataset in d3如何在 d3 中访问数据集中的元素
【发布时间】:2020-09-17 10:53:37
【问题描述】:

我有一个平行坐标图,我想为 onclick 显示线 d.dataset = train 否则隐藏它们。

我想像这样使用.filter() 访问该行:

data.filter(function(d) { return d.dataset == "train"; }).attr("visibility", "hidden");

然后将 attr 可见性设置为隐藏,以便之后我可以使用 onclick 编写一个函数以使可见性可见,如下所示:

   // On Click, we want to add data to the array and chart
      svg.on("click", function() {
          var line = d3.mouse(this);

                    if (d.dataset === "train"){
                
              //Display line of d.dataset === train 
              // line.attr("visibility", "visible");
              
          }
        });

我也找到了这个d3.selectAll("[dataset=train]").attr("visibility", "hidden");,但这在处理数据元素时不起作用,对吧?

现在我尝试了这些,但没有任何反应。这是我正在工作的jsfiddle"dataset":"train", 的行是可见的,不会隐藏。

如何在"dataset":"train", 时隐藏线条,然后在onclick 时将它们显示到平行坐标图中的其他线条?

任何帮助将不胜感激。

【问题讨论】:

  • 你是不是要先隐藏 train 的线路,然后点击其他线路时显示?
  • @soundquiet 是的。我就是这样。

标签: javascript d3.js


【解决方案1】:

首先,在每条路径上做一些标记,例如,给一个类名,如coorPath,这样更容易找到它们。我为backgroundforeground 添加了它,因为我不知道它们的区别。

    svg.append("g")
        .attr("class", "background coorPath") // add classname
        .selectAll("path")
        .data(dataSet)
        .enter().append("path")
        .attr("d", draw);

    // CHANGE: duplicate with below code
    /* svg.append("g") 
        .attr("class", "foreground coorPath")
        .selectAll("path")
        .data(dataSet)
        .enter().append("path")
        .attr("d", draw); */

    // USE THE COLOR SCALE TO SET THE STROKE BASED ON THE DATA
    foreground = svg.append("g")
        .attr("class", "foreground coorPath")
        .selectAll("path")
        .data(dataSet)
        .enter().append("path")
        .attr("d", draw)
        .style("stroke", function(d) {
            var company = d.type.slice(0, d.type.indexOf(' '));
            return color(company);
        })

然后,找出火车的路线,先让它不可见

   let trainline = d3.selectAll("path").filter(function(d) { return d.dataset == "train"; })
   trainline.attr("visibility", "hidden");

点击其他线路之一时显示火车线路。

   svg.selectAll(".coorPath").on("click", function(d) {
      // show train when click others
      trainline.attr("visibility", "visible")
   });

a demo here

【讨论】:

  • 非常感谢!我非常感谢你的帮助。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-23
  • 2017-01-20
  • 1970-01-01
  • 2016-02-23
  • 2020-02-21
  • 1970-01-01
  • 2016-07-19
相关资源
最近更新 更多