首页 > 解决方案 > 工具提示位于 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!
        });

标签: javascriptcssangulard3.js

解决方案


使用事件的layerXandlayerY来定位您的工具提示:

.on("mouseover", (event, d) => {
  tooltip
    .html(...)
    .style('left', event.layerX)
    .style('top', event.layerY)
    .transition()
    ...
})

推荐阅读