我正在使用D3.js.我想顯示一個工具提示與相應的Y軸值,當我mouseover d3.svg.line()。如何使用d3.js在mouseover svg線圖上顯示值的工具提示?
我嘗試使用此代碼:
d3.svg.line().append("title")
.text(function(d) { return d; });`
但它拋出錯誤有沒有方法 '追加'。有沒有其他方法?
我正在使用D3.js.我想顯示一個工具提示與相應的Y軸值,當我mouseover d3.svg.line()。如何使用d3.js在mouseover svg線圖上顯示值的工具提示?
我嘗試使用此代碼:
d3.svg.line().append("title")
.text(function(d) { return d; });`
但它拋出錯誤有沒有方法 '追加'。有沒有其他方法?
d3.svg.line()是一個線條生成器;它不是實際的線元素。此功能可用於區域生成器,但您可以通過使用「填充:無」來禁用內部形狀的外觀。有關更多詳細信息,請參閱其文檔鏈接:https://github.com/mbostock/d3/wiki/SVG-Shapes#wiki-line。
下面的代碼使用d3.svg.line()生成器創建一個路徑元素,然後向其生成的路徑添加工具提示。該標題的文本屬性顯示鼠標在哪裏的y值。這是通過使用鼠標事件「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]);
}
這個代碼僅給出兩個參數X和Y,但我有我想要顯示它的路徑懸停一些數據陣列,怎能將任何可能的想法? –
函數mMove可以接收「d」參數。這個「d」參數是您懸停的數據元素。 – zenw0lf
這是3.0前的代碼。根據https://github.com/mbostock/d3/wiki/Upgrading-to-3.0#svg,應該使用d3.mouse(this)。 –