[英]Multiline chart d3 tooltip
我正在嘗試向多線圖表添加工具提示,但我無法按照我想要的方式對其進行格式化。 目前,我在連接點處獲取工具提示文本,但我想獲取頂部rect
內的所有點數據,就像我在圖表中使用 d3 的示例圖像一樣。 這是mousemove上的一段代碼。
.on('mousemove', function (e) { // mouse moving over canvas
const mouse = e.clientX;
d3.select(".mouse-line-" + chart_sel)
.attr("d", function () {
var d = "M" + mouse + "," + height;
d += " " + mouse + "," + 0;
return d;
});
d3.selectAll(".mouse-per-line-" + chart_sel)
.attr("transform", function (d, i) {
var xDate = x.invert(mouse),
bisect = d3.bisector(function (d) { return d.date; }).right;
idx = bisect(d.values, xDate);
d3.select(".mouse-line-" + chart_sel)
.attr("d", function () {
var data = "M " + x(d.values[idx].date) + "," + (height);
data += "L " + x(d.values[idx].date) + "," + 0;
return data;
});
var beginning = 0,
end = lines[i].getTotalLength(),
target = null;
while (true) {
target = Math.floor((beginning + end) / 2);
pos = lines[i].getPointAtLength(target);
if ((target === end || target === beginning) && pos.x !== mouse[0]) {
break;
}
if (pos.x > mouse[0]) end = target;
else if (pos.x < mouse[0]) beginning = target;
else break; //position found
}
d3.select(this).select('text')
.text(Math.round(y.invert(pos.y)))
.style("text-anchor", "start")
return "translate(" + x(d.values[idx].date) + "," + y(d.values[idx].value) + ")";
});
})
這是codepen中代碼的鏈接。
這是工具提示的示例
提前致謝!
我在您的筆中發現了一些錯誤:
您不能在 D3.V6 中使用d3.pointer(this)
。 相反,從 mousemove 回調參數中獲取指針 position:
.on('mousemove', e => {
const x = e.clientX; // instead of mouse[0]
...
}
您格式化的路徑字符串有'M' (移動到)但沒有'L' (行到)指令,應該是'M x,y L x,y' :
var data = "M " + x(d.values[idx].date) + "," + (height);
data += "L " + x(d.values[idx].date) + "," + 0;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.