【问题标题】:Selecting all elements in one group of a categorical variable选择一组分类变量中的所有元素
【发布时间】:2016-02-24 16:48:55
【问题描述】:

我有一个基于this 示例的散点图。当鼠标悬停在任何单个点上时,我想突出显示一种颜色的所有点。 Aka,如果我将鼠标悬停在一个绿点上,所有绿点会切换为完全不透明。

我在这里做了一个小提琴:https://jsfiddle.net/nancynancy/mc3tz3dj/55/

据我了解,我的代码目前只选择一个点,所以我认为我需要为物种变量的每个类别创建一个组——但我不确定它是什么样的。在 R 中,species 变量将是具有不同级别的因素; D3 中的类比是什么?

  // Part of the plot function 
  chart.selectAll(".dot")
      .data(params.data)
    .enter().append("circle")
      .attr("class", "dot")
      .attr("r", function(d){ return responseScale(d.petalWidth);})
      .attr("cx", function(d) { return x(d.sepalWidth); })
      .attr("cy", function(d) { return y(d.sepalLength); })
      .style("fill", function(d) { return color(d.species);});

 // Create a group here, say ".species" that will replace ".dot"? 

 this.selectAll(".dot")
        .on("mouseover", function(d){
        d3.select(this)
                    .transition()
                    .style("opacity", 1)
      })
      .on("mouseout", function(d){
        d3.select(this)
                    .transition()
                    .style("opacity", 0.1)
      });

【问题讨论】:

    标签: d3.js mouseover


    【解决方案1】:

    我可能会“全选”这些点,然后过滤选择以仅包含物种属性与鼠标悬停点匹配的那些点

    chart.selectAll(".dot")
        .on("mouseover", function(d){
            d3.selectAll('.dot')
                .filter(function(dot){ 
                    return (dot.species == d.species) 
                })
                .transition()
                .style("opacity", 1)
          })
       .on("mouseout", function(d){
            d3.selectAll('.dot')
                .filter(function(dot){ 
                    return (dot.species == d.species) 
                })
                .transition()
                .style("opacity", 0.1)
          });
    

    另外请注意,我倾向于尽可能避免使用this,因为它的值可能会根据包含函数的调用站点而改变——这会使重构变得尴尬

    JS Fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-13
      • 2017-08-10
      • 2021-08-17
      • 2015-09-28
      • 1970-01-01
      • 1970-01-01
      • 2012-01-07
      • 2013-11-04
      相关资源
      最近更新 更多