如何将鼠标悬停在一个图表上以在 D3.js 中的所有图表上显示垂直线和工具提示?

How to hover over one chart to display a vertical line and tooltip on all charts in D3.js?

我正在使用 D3.js 和 ReactJS 我想将鼠标悬停在一个图表上并在所有其他图表上显示一条垂直线和工具提示。

我一次只能在一个图表中获取垂直线。 预期结果是在所有图表中显示垂直线和工具提示。

这是我尝试过的:

  React.useEffect(() => {
    d3.select(anchorEl)
      .on("mouseout.tooltip", () => {
        d3.select(ref.current).attr("opacity", 0);
      })
      .on("mouseover.tooltip", () => {
        d3.select(ref.current).attr("opacity", 1);
      })
      .on("mousemove.tooltip", (e) => {
        d3.select(ref.current)
          .selectAll(".tooltipLinePoint")
          .attr("opacity", 1);
        followPoints(e);
      });
  }, [anchorEl, followPoints]);

这是实际的代码结果multiline-chart-tooltip-acoss-all-charts

解决方法:

为当前悬停的图表画线,然后为其他图表画线,关键是使用d3.select()和d3.selectAll()。

  d3.select(ref.current)
    .select(".tooltipLine")
    .attr("x1", x)
    .attr("x2", x)
    .attr("y1", -margin.top)
    .attr("y2", height);

  d3.selectAll(".tooltip")
    .select(".tooltipLine")
    .attr("x1", x)
    .attr("x2", x)
    .attr("y1", -margin.top)
    .attr("y2", height);

  drawLine(baseXPos);
  drawContent(baseXPos);
  drawBackground();

  drawLineForOthers(baseXPos);
  drawContentForOthers(baseXPos);
  drawBackgroundForOthers();