[英]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.