javascript - React ChartJS 流式传输实时数据

标签 javascript reactjs chart.js react-chartjs

我正在尝试使用 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>
  );
};

enter image description here

最佳答案

这是因为您将比例定义为数组而不是对象。这在 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,
    },
  },
}

关于javascript - React ChartJS 流式传输实时数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69707161/

相关文章:

javascript - 推特位置未定义

javascript - Firebase 时间戳过滤器

javascript - 在 react 中将值传递给子组件(this.props.children)

reactjs - react useMemo 内存清理

javascript - 无法读取未定义的属性 'Concat'

javascript - 从打印预览中删除输入框

reactjs - 操作和状态显示在控制台上,但在带有 React Hook 的应用程序上未定义

javascript - 我的代码有什么问题? javascript图表位置

javascript - 雷达 chartjs 上的渐变背景

javascript - 使用 JavaScript 覆盖 Google map API 中标记弹出窗口上的默认文本?