我正在使用 D3.js。当我将鼠标悬停在 d3.svg.line() 上时,我想显示一个带有相应 Y 轴值的工具提示。
我尝试使用此代码:
d3.svg.line().append("title")
.text(function(d) { return d; });`
但它抛出错误has no method 'append'。还有其他方法吗?
d3.svg.line() 是一个线生成器;它不是实际的线元素。此功能旨在与区域生成器一起使用,但您可以使用“fill:none”禁用其中的形状外观。有关更多详细信息,请参阅其文档的链接:https ://github.com/mbostock/d3/wiki/SVG-Shapes#wiki-line 。
下面的代码使用 d3.svg.line() 生成器创建一个路径元素,然后将工具提示添加到它生成的路径中。此标题的文本属性显示鼠标所在位置的 y 值。这是通过使用鼠标事件“mousemove”完成的,这似乎是您想要的,而不是使用“mouseover”。(鼠标悬停需要您移入和移出形状以更新文本值,而即使您的鼠标沿线移动,mousemove 也会更改该值。)
var data = [[{x:100, y:200}, {x:0,y:400}, {x:2, y:300}]];
var line = d3.svg.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
.interpolate("basis");
var svg = d3.select("body").append("svg:svg")
.attr("width", 400)
.attr("height", 400);
var g = svg.selectAll("g").data(data).enter().append("svg:g")
.attr("width", 400)
.attr("height", 400);
g.append("path")
.attr("d", line)
.attr("id", "myPath")
.attr("stroke", "black")
.attr("stroke-width", 5)
.attr("fill", "none") // Remove this part to color the
// shape this path produces
.on("mousemove", mMove)
.append("title");
function mMove(){
var m = d3.svg.mouse(this);
d3.select("#myPath").select("title").text(m[1]);
}
你的回答有一点错误。
d3.svg.mouse(this)
不起作用。
正确答案是
d3.mouse(this)