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

标签 javascript jquery d3.js data-visualization

我有一个散点图类似于: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 以外的组合返回正确的工具提示。

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

最佳答案

为此:

首先将工具提示信息存储在一个新变量(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

希望这对您有所帮助!

关于javascript - 为 D3 中的动态数据生成工具提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35472426/

相关文章:

asp.net - 验证后将焦点设置为验证摘要控制时出现问题

php - jquery根据另一个输入值自动完成sql查询列表

javascript - 如何从 d3 列表中删除所选项目

javascript - dc.js:更改 x 轴增量

javascript - 将 iframe 高度设置为内部内容的高度(在同一域上)

javascript - 在使用 ajax 显示之前加载 TXT 文件

javascript - jQuery appendTo 列表框在 IE 中不起作用

jquery - 根据环境有条件地选择jquery的版本

javascript - 如何在外部js中编写blade语法

css - 将省略号添加到 SVG 中的溢出文本?