鼠标悬停时创建一条连接圆圈的线

时间:2013-10-25 19:50:42

标签: d3.js

我在D3中制作了散点图,其中圆圈表示每个数据点。这是我的代码:

viz.selectAll('circle')
  .data(data)
  .enter()
  .append('circle')
  .attr("cx", function(d) {return x(d.x)})
  .attr("cy", function(d) {return y(d.y)})
  .attr("r", 5)
  .attr("fill", function(d) {return d.color})
  .on('mouseover', function(d){
      console.log(d.color)
  })

我想要做的是,当一个特定的圆圈悬停在上面时,通过一条颜色相同的线连接所有圆圈。我怎样才能做到这一点?我可以将颜色记录到控制台中,但是我不明白如何在点击鼠标时通过一条线连接所有相同颜色的点?

2 个答案:

答案 0 :(得分:2)

您可以为圈子指定带有颜色代码的班级。使用d3.selectAll在鼠标悬停时检索所有这些内容。然后检索它们的坐标并传递坐标以绘制d3.svg.line。

svg.selectAll(".dot")
    .data(data)
  .enter().append("circle")
    .attr("class", function(d) {
        return 'dot color-' + color(d.species).replace('#','');
      })
    .attr("r", 3.5)
    .attr("cx", function(d) { return x(d.sepalWidth); })
    .attr("cy", function(d) { return y(d.sepalLength); })
    .attr("dot-color", function(d) { return color(d.species).replace('#',''); })
    .style("fill", function(d) { return color(d.species); })
    .on("mouseover", function() {
        d3.selectAll(".color-" + $(this).attr("dot-color"))
          .attr("r", 5.5);
    })
    .on("mouseout", function() {
        d3.selectAll(".color-" + $(this).attr("dot-color"))
          .attr("r", 3.5);
    });

以下是颜色悬停的示例:

http://vida.io/documents/KinEKRkSPSfStA4Eu

答案 1 :(得分:1)

您也可以在不依赖公共类属性的情况下执行此操作。在鼠标悬停处理程序中:

d3.selectAll('.dot')
  .filter(function (dOther) { return d.color == dOther.color })
  .attr('r', 3.5)
相关问题