为 D3 中的动态数据生成工具提示

Generating tool-tip for dynamic data in D3

我的散点图类似于:http://plnkr.co/edit/MkZcXJPS7hrcWh3M0MZ1?p=preview

我想为每个组合提供鼠标悬停时的工具提示。我目前拥有的工具提示代码确实像:

var tooltip = d3.select("body").append("div")  // tooltip code
   .attr("class", "tooltip")
   .style("opacity", 0);

 var circles = svg.selectAll(".dot")
      .data(data)
    .enter().append("circle")
      .attr("class", "dot")
      .attr("r", 3.5)
      .attr("cx", function(d) { return x(d.petalWidth); })
      .attr("cy", function(d) { return y(d.petalLength); })
      .style("fill", function(d) { return color(d.species); })
      .on("mouseover", function(d) {
         tooltip.transition()
            .duration(200)
            .style("opacity", 1.0);
         tooltip.html(d.petalLength+", "+d.petalWidth)
            .style("left", (d3.event.pageX + 5) + "px")
            .style("top", (d3.event.pageY - 18) + "px");
      })
      .on("mouseout", function(d) {
         tooltip.transition()
            .duration(500)
            .style("opacity", 0);
      });

对于 petalWidth 和 d.petalLength 以外的组合,这将无法 return 正确的工具提示。

有没有办法知道选择了哪个组合以及该组合的相关数值?

为此:

首先将工具提示信息存储在一个新变量(displayX/displayY)中,如下所示:

.attr("cx", function(d) {
          d.displayX = d.petalWidth;//so displayX holds the x info
          return x(d.petalWidth);

        })
        .attr("cy", function(d) {
          d.displayY = d.petalLength;//so displayY holds the y info
          return y(d.petalLength);
        })

设置组合时相应地重置变量。

 svg.selectAll(".dot").transition().attr("cy", function(d) {
          d.displayY = d[yAxy];//reset the variable displayY
          return y(d[yAxy]);
        });

也一样
svg.selectAll(".dot").transition().attr("cx", function(d) {
  d.displayX = d[xAxy];//reset the variable displayX
  return x(d[xAxy]);
});

现在在工具提示中鼠标悬停使用变量(displayX/displayY)

 .on("mouseover", function(d) {
          tooltip.transition()
            .duration(200)
            .style("opacity", 1.0);
          tooltip.html(d.displayY + ", " + d.displayX)//use displayX and displayY
            .style("left", (d3.event.pageX + 5) + "px")
            .style("top", (d3.event.pageY - 18) + "px");
        })
        .on("mouseout", function(d) {
          tooltip.transition()
            .duration(500)
            .style("opacity", 0);
        });

工作代码here

希望对您有所帮助!