我使用此示例创建堆积条形图。图表工作并呈现,但我无法添加鼠标悬停标签。
我试过这个...
DATE.selectAll("rect")
.data(function(d) { return d.ages; })
.enter().append("rect")
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.y1); })
.attr("height", function(d) { return y(d.y0) - y(d.y1); })
.style("fill", function(d) { return color(d.name); });
.append("svg:title")
.text(functino(d){return "foo"});
但是在添加.append("svg:title...
后,图形将停止渲染。如果我删除.style("fill...
线,图形将呈现,但它不会堆叠并且没有鼠标悬停功能。
我也尝试使用工具提示路由。(来源)
.on("mouseover", function() { tooltip.style("display", null); })
.on("mouseout", function() { tooltip.style("display", "none"); })
.on("mousemove", function(d) {
var xPosition = d3.mouse(this)[0] - 15;
var yPosition = d3.mouse(this)[1] - 25;
tooltip.attr("transform", "translate(" + xPosition + "," + yPosition + ")");
tooltip.select("text").text(d.y);
});
// Prep the tooltip bits, initial display is hidden
var tooltip = svg.append("g")
.attr("class", "tooltip")
.style("display", "none");
tooltip.append("rect")
.attr("width", 30)
.attr("height", 20)
.attr("fill", "white")
.style("opacity", 0.5);
tooltip.append("text")
.attr("x", 15)
.attr("dy", "1.2em")
.style("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold");
但仍然不是运气。是否有我需要加载的库?不知道发生了什么。
当您尝试附加title
时,图形会停止呈现,因为您有一个拼写错误:它是function
,而不是functino
。
除此之外,这是获取每个堆叠条形图的值所需的:
.append("title")
.text(function(d){
return d[1]-d[0]
});
这是演示:https://bl.ocks.org/anonymous/raw/886d1749c4e01e191b94df23d97dcaf7/
但我不喜欢<title>
。它们不是很通用。因此,与其像您链接的第二个代码那样创建另一个<text>
,我更喜欢创建一个div:
var tooltip = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
我们以这种方式定位和设置 HTML 文本:
.on("mousemove", function(d) {
tooltip.html("Value: " + (d[1] - d[0]))
.style('top', d3.event.pageY - 10 + 'px')
.style('left', d3.event.pageX + 10 + 'px')
.style("opacity", 0.9);
}).on("mouseout", function() {
tooltip.style("opacity", 0)
});
这是演示:https://bl.ocks.org/anonymous/raw/f6294c4d8513dbbd8152770e0750efd9/