首页 > 解决方案 > 将鼠标悬停在图表上时 react-chartjs-2 垂直线

问题描述

我正在尝试使用 react-chartjs-2 创建一个折线图,当将鼠标悬停在图表中的数据点上时,它有一条垂直线。如下图所示:

图表要求

我尝试使用 chartjs-plugin-annotation 插件,但结果好坏参半。我设法创建了一条静态线,但不了解它的工作方式或原因。我应该如何实现这一目标?我有什么事吗?

const data = {
    labels: [...week(d)],
    datasets: [
        {
            ...
            data: [10000, 9500, 7000, 4500, 2500, 1500, 500, 0],
        }
    ]
};

var line = [{
    type: "line",
    mode: "vertical",

    // ???
    scaleID: "y-axis-0",
    value: -20000,

    borderColor: "#2984c5",
    borderWidth: 1,
}];

const options = {
    tooltips: {
        xPadding: 20,
        yPadding: 10,
        displayColors: false,
        bodyFontSize: 16,
        bodyFontStyle: 'bold',
    },
    annotation: {
        annotations: line,
    },
    scales: {
        yAxes: [{
            gridLines: {
                drawBorder: false,
                tickMarkLength: 0,
            },
            ticks: {
                fontSize: 14,
                padding: 15,
                max: data.maxY,
                min: 0,
                maxTicksLimit: 6,
                fontColor: "#485465"
            }
        }],
        xAxes: [{
            ticks: {
                padding: 5,
                fontSize: 14,
                fontColor: "#485465",
            },
            gridLines: {
                display: false,
            },
        },

        ],
    },
    responsive: false,
}

我在这里有我的完整代码:https ://codesandbox.io/s/y28mk3rn4z

标签: reactjschartjs-2.6.0react-chartjs

解决方案


刚刚调查了这个确切的事情,这会让你到达那里!它不会在线条的任一侧进行填充,但会创建垂直线!

componentWillMount() {
    Chart.pluginService.register({
      afterDraw: function (chart, easing) {
        if (chart.tooltip._active && chart.tooltip._active.length) {
          const activePoint = chart.controller.tooltip._active[0];
          const ctx = chart.ctx;
          const x = activePoint.tooltipPosition().x;
          const topY = chart.scales['y-axis-1'].top;
          const bottomY = chart.scales['y-axis-1'].bottom;
          ctx.save();
          ctx.beginPath();
          ctx.moveTo(x, topY);
          ctx.lineTo(x, bottomY);
          ctx.lineWidth = 2;
          ctx.strokeStyle = '#e23fa9';
          ctx.stroke();
          ctx.restore();
        }
      }
    });
  }

此外,对于拥有多个数据集的任何人,您都可以一次将其添加到所有行的工具提示选项中。

tooltips: {
          mode: 'x'
        },

推荐阅读