我正在尝试向多折线图添加工具提示,但无法按照我想要的方式对其进行格式化。目前我在连接点获得工具提示文本,但我想在顶部的 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 中代码的链接。
这是工具提示的示例
提前致谢!
答案 0 :(得分:0)
我发现你的笔有一些错误:
您不能在 D3.V6 中使用 d3.pointer(this)
。相反,从 mousemove 回调参数中获取指针位置:
.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;