我无法弄清楚为什么在条形图后面绘制了工具提示。我知道在SVG中最上一层是最近添加的一层,但是我无法弄清楚为什么我的工具提示(尽管是在绘制条形的代码之后添加的)却被绘制在我尝试使用的图表的条形后面:d3.select (“ .toolTip”)。Raise()和d3.select(“。bars”)。lower()全部无效。任何解决方案或建议将不胜感激。
function drawChart(){
svg.append("g")
.selectAll("g")
.data(series)
.enter().append("g")
.attr("fill", function(d) {
colors[d.key] = z(d.key);
return z(d.key); })
.selectAll("rect")
.data(function(d) { return d; })
.enter().append("rect")
.attr("class","bars")
.attr("width", xScale.bandwidth)
.attr("x", function(d) { return xScale(d.data.date); })
.attr("y", function(d) { return yScale(d[1]); })
.on("mousemove", mousemove)
.on("mouseout", mouseout)
.attr("height", function(d) { return yScale(d[0]) - yScale(d[1]); })
tooltip = g.append("rect")
.attr("class", "toolTip")
.style("fill","#ffffff")
.style("display","none")
.style("stroke"," #6F257F")
.attr("width",100)
.attr("height",130)
}
function mouseout(){
d3.select(".toolTip").style("display", "none");
d3.select(".toolTipText").remove()
d3.select(".toolTipChart").remove()
}
// custom invert function as D3 invert does not work on ordinal scales yet(as of 2019 March)
xScale.invert = (function(){
var domain = xScale.domain()
var range = xScale.range()
var scale = d3.scaleQuantize().domain(range).range(domain)
return function(x){
return scale(x)
}
})()
function mousemove(){
d3.select(".toolTipText").remove()
d3.select(".toolTipChart").remove()
var xy = d3.mouse(eventCapture.node())
var d = xScale.invert(xy[0])
d3.select(".toolTip")
.attr("x", d3.event.pageX + "px")
.attr("y", d3.event.pageY + "px")
.style("display", "inline-block")
g.append("text")
.attr("class","toolTipText")
.attr("x", d3.event.pageX+20 + "px")
.attr("y", d3.event.pageY +30 + "px")
.text(function(){return `£${netAggregatedPosition[d]}m`})
g.append("rect")
.attr("class","toolTipChart")
.attr("x",d3.event.pageX +20+ "px")
.attr("y",d3.event.pageY +40+"px")
.attr("width",20)
.style("fill",function(){
if(netAggregatedPosition[d]>0 || netAggregatedPosition[d]==0)
{
return "green";
}else{
return "red";
}})
.transition()
.duration(1000)
.attr("height",toolTipScale(Math.abs(netAggregatedPosition[d]))/4)
}