我有一个散点图类似于: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/