javascript - 工具提示位于 d3.js 中 svg 的底部
问题描述
我在 d3 图表(散点图、折线图等)上放置了一个工具提示。问题是它们都是底部对齐的,如下图所示。我需要它们出现在圆圈上方。起初,我想也许我正在使用 ngx-bootstrap 工具提示,所以引导工具提示类可能会覆盖我在图表中使用的工具提示类,但事实并非如此。
如何做到这一点?
代码 :
let div = d3
.select(this.chartElem.nativeElement)
.select(".linechart")
.append("div")
.attr("class", "tooltip")
.style("opacity", 0)
.attr("class", "tooltip")
.style("background-color", "white")
.style("border", "solid")
.style("border-width", "1px")
.style("border-radius", "5px")
.style("padding", "10px");
this.svgInner
.selectAll(".svg-container")
.data(this.data1)
.enter()
.append("circle")
.attr("class", "dot")
.attr("fill", (d) => {
if ((d.age - 10) * (d.age - 19) <= 0) {
return "#042F5B ";
}
if ((d.age - 20) * (d.age - 29) <= 0) {
return "#053E78 ";
}
if ((d.age - 30) * (d.age - 39) <= 0) {
return "#074E95 ";
}
if ((d.age - 40) * (d.age - 49) <= 0) {
return "#0964C0";
}
if ((d.age - 50) * (d.age - 59) <= 0) {
return "#0E81F4 ";
}
if ((d.age - 50) * (d.age - 59) <= 0) {
return "#4DA0F3";
}
if ((d.age - 60) * (d.age - 69) <= 0) {
return "#77B4F1";
}
})
.attr("data-xvalue", (d) => d.p1)
.attr("data-yvalue", (d) => d.p2)
.attr("cx", (d) => {
return this.xScale(d.p1);
})
.attr("cy", (d) => this.yScale(d.p2))
.attr("r", 4)
.on("mouseover", (event, d: any) => {
tooltip
// started as 0!
.html(
"PC1: " +
d.p1+
"<br>" +
"PC2: " +
d.p2
)
/* .style("left", d3.pointer(this)[0] + 90 + "px") // It is important to put the +90: other wise the tooltip is exactly where the point is an it creates a weird effect
.style("top", d3.pointer(this)[1] + "px") */
.transition()
.duration(200) // ms
.style("opacity", 0.9);
})
.on("mouseout", (event, d) => {
tooltip
.transition()
.duration(300) // ms
.style("opacity", 0); // don't care about position!
});
解决方案
使用事件的layerX
andlayerY
来定位您的工具提示:
.on("mouseover", (event, d) => {
tooltip
.html(...)
.style('left', event.layerX)
.style('top', event.layerY)
.transition()
...
})
推荐阅读
- python - 将动画对象附加到列表时不发生动画
- visual-studio-code - 有没有办法告诉 VSCode .vscode 文件夹在哪里?
- laravel - 计数相同值 Laravel 集合
- elasticsearch - 删除 Elasticsearch 快照
- fragmentpageradapter - 如何扩展 FragmentPagerAdapter 类?
- c# - 我正在创建 Xamarin,我尝试将数组转换为字符串但我无法将数组转换为字符串
- kotlin - Kotlin Flow 的 Collect 是否只是内部 kotlinx.coroutines API?
- php - 具有不同参数的 phpspec/prophecy 存根方法调用
- android - Android MediatorLiveData removeSource 不起作用
- jinja2 - 在 html 中使用 jinja2 来根据环境变量控制要加载的 javascript