react-chartjs-2 vertical line when hovering over chart

风格不统一 提交于 2021-01-28 00:51:37

问题


I'm trying to create a linechart, using react-chartjs-2, that has a vertical line when hovering over the datapoints in the chart. Like in this picture below:

Chart requirements

I tried using the chartjs-plugin-annotation plugin, but with mixed results. I managed to create a static line, not understanding how or why it works. How should I achieve this? Am I onto something?

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,
}

I have my full code available here: https://codesandbox.io/s/y28mk3rn4z


回答1:


Just looked into this exact thing and this will get you there! It won't do the fills on either side of the line, but it creates the vertical line!

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();
        }
      }
    });
  }

Also for anyone with multiple datasets you can add this into your options for tooltips on all lines at once.

tooltips: {
          mode: 'x'
        },


来源:https://stackoverflow.com/questions/55300288/react-chartjs-2-vertical-line-when-hovering-over-chart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!