Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...