Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.2k views
in Technique[技术] by (71.8m points)

javascript - I want delete the values from the series so that the graph is not cluttered how to do that

import { render } from "react-dom";
import HighchartsReact from "highcharts-react-official";
import Highcharts from "highcharts";

const LineChart = () => {
  const [chartOptions, setChartOptions] = useState({
    series: [{ data: [1, 2, 3] }]
  });

  const [intervalRef, setIntervalRef] = useState(null);

  function toggleLiveData() {
    if (!intervalRef) {
      setIntervalRef(setInterval(() => {
      console.log("add");
      setChartOptions((state) => ({
        series: [
          {
            data: [...state.series[0].data, Math.random()]
          }
        ]
      }));
    }, 500));

    } else {
      clearInterval(intervalRef);
      setIntervalRef(null);
    }
  }
  function handleClick() {
    toggleLiveData();
  }

  return (
    <div>
      <HighchartsReact highcharts={Highcharts} options={chartOptions} />
      <button onClick={handleClick}>toggle live data</button>
    </div>
  );
};

render(<LineChart />, document.getElementById("root"));

This code dynamically adds points to the chart. It adds the new point every 1/2second and after a point it just clutters the graph how do I remove the extra points and only keep 10 points on the screen at once?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In this case the best is get a chart reference and call the addPoint method directly on a series (with enabled the shift argument).

const LineChart = () => {
  ...

  function toggleLiveData() {
    if (!intervalRef) {
      setIntervalRef(
        setInterval(() => {
          if (chartComponent.current) {
            chartComponent.current.chart.series[0].addPoint(
              Math.random(),
              true,
              true,
              false
            );
          }
        }, 500)
      );
    } else {
      clearInterval(intervalRef);
      setIntervalRef(null);
    }
  }

  return (
    <div>
      <HighchartsReact
        ref={chartComponent}
        highcharts={Highcharts}
        options={chartOptions}
      />
    </div>
  );
};

Live demo: https://codesandbox.io/s/highcharts-react-demo-forked-58ptz?file=/demo.jsx

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...