Search code examples
javascriptreactjshighchartsreact-functional-componentreact-highcharts

Inconsistent Data Points in HighCharts Scatter Plot with ReactJS


Previousy, I was using line charts. but now, I want multiple data points on same X-Axis with tooltip, and according to HighCharts behaviour -

"In a line chart, by default, Highcharts will display the tooltip for the last data point when multiple data points share the same x-axis value."

In order to achieve this behaviour, I have converted my chart to 'Scatter'.

=> I have a scatter plot (data points connected with a series line). Page load consistently plots correctly, but updating with new series data brings unexpected data points in the graph.

Expected behaviour : Plot consistently when updating with new series data

Actual behaviour : Inconsistent data points show up depending on previous series data.

I have researched about this and found this links which shows this was the issue with HighCharts and a way to resolve the same:

  1. https://github.com/highcharts/highcharts/issues/9184

  2. https://github.com/highcharts/highcharts/issues/9037

But, I am not able to figured out how can i solve this with ReactJS. Here is my code: https://stackblitz.com/edit/react-9wsnd9?file=index.js


Solution

  • To use the suggested workaround with React, you need to get the chart instance and call setData on series. For example:

      useEffect(() => {
        const chart = chartRef.current.chart;
        if (chart) {
          chart.series[0].setData(mainData, true, true, false);
        }
      }, [data]);
    

    Live demo: https://stackblitz.com/edit/react-jiva32?file=index.js

    Docs: https://github.com/highcharts/highcharts-react#how-to-get-a-chart-instance

    API Reference: https://api.highcharts.com/class-reference/Highcharts.Series#setData