我正在使用D3.js.当我将鼠标移到d3.svg.line()时,我想显示一个带有相应Y轴值的工具提示。
我尝试使用此代码:
d3.svg.line().append("title")
.text(function(d) { return d; });`
但是它会抛出错误没有方法'追加'。还有其他办法吗?
答案 0 :(得分:11)
d3.svg.line()是一个线生成器;它不是实际的线元素。此功能旨在与区域生成器一起使用,但您可以使用“fill:none”禁用内部形状的外观。有关更多详细信息,请参阅其文档的链接:https://github.com/mbostock/d3/wiki/SVG-Shapes#wiki-line。
下面的代码使用d3.svg.line()生成器创建一个path元素,然后将工具提示添加到它生成的路径中。此标题的文本属性显示鼠标所在位置的y值。这是通过使用鼠标事件“mousemove”来完成的,这似乎更像是你想要的而不是使用“mouseover”。 (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]);
}
答案 1 :(得分:10)
你的回答有点错误。
d3.svg.mouse(this)
不起作用。
正确的答案是
d3.mouse(this)