React chartJS 流式传输实时数据

React chartsJS streaming live data

我正在尝试使用 Chartjs 构建 React ChartsJS 实时数据流 我设法在页面上呈现 canvas 但出于某种原因,我仍然无法像实时一样移动折线图数据 我不确定是否需要将任何内容嵌入 HTML 页面。我安装了这些软件包:chart.js "chartjs-adapter-luxon": "^1.1.0 "chartjs-plugin-streaming": "^2.0.0" 我希望有人能帮助我!

import React from "react";
import { Line } from "react-chartjs-2";
import Chart from "chart.js/auto";
import { StreamingPlugin, RealTimeScale } from "chartjs-plugin-streaming";
Chart.register(StreamingPlugin, RealTimeScale);

export const IotChart = () => {
  const data = {
    datasets: [
      {
        label: "Dataset 1",

        fill: false,
        lineTension: 0.4,
        backgroundColor: "#f44336",
        borderColor: "#f44336",
        borderJoinStyle: "miter",
        pointRadius: 0,
        showLine: true,
        data: [] as any,
      },
    ],
  };

  const options = {
    scales: {
      xAxes: [
        {
          type: "realtime",
          realtime: {
            onRefresh: function () {
              data.datasets[0].data.push({
                x: Date.now(),
                y: Math.random() * 100,
              });
            },
            delay: 300,
            refresh: 300,
          },
        },
      ],
      yAxes: [
        {
          scaleLabel: {
            display: true,
            fontFamily: "Arial",
            labelString: "Moment",
            fontSize: 20,
            fontColor: "#6c757d",
          },
          ticks: {
            max: 100,
            min: 0,
          },
        },
      ],
    },
  } as any;

  return (
    <div>
      <div>
        <Line data={data} options={options} width={400} height={200} />
      </div>
    </div>
  );
};

这是因为您将比例定义为数组而不是对象。这在 V3 中已更改,对于所有更改,请阅读 migration guide 因为有更多重大更改,例如 Y 轴刻度标签字体声明。

如果您检查流式传输 documentation/examples,您还会看到它被定义为对象。

因此更改为此将解决您的问题:

scales: {
  x: {
    type: "realtime",
    realtime: {
      onRefresh: function() {
        data.datasets[0].data.push({
          x: Date.now(),
          y: Math.random() * 100,
        });
      },
      delay: 300,
      refresh: 300,
    },
  },
}