【问题标题】:real time scrolling based chart with chart.js使用 chart.js 的实时滚动图表
【发布时间】:2021-09-24 18:05:28
【问题描述】:

我想创建带有滚动时间的实时图表,例如以下视频:https://www.youtube.com/watch?v=2-tnkzG0sKU

chart.js 可以做到这一点吗?到目前为止,我有以下内容,它正在滚动但时间没有显示,我想以秒为单位显示。

let dataSize = 500;
let readings = new Array(dataSize);    
// data object for the chart:
const data = {
  // X axis labels
  labels: new Array(),
  datasets: [{
    data: readings,         // the data to chart
    borderColor: '#272323', // line color (lavender)
    pointRadius: 0.5          // point size
  }]
};

const config = {
  type: 'line',         // type of chart
  data: data,           // the data
  options: {
    animation: false,   // remove animation to speed drawing up
    responsive: true,
    maintainAspectRatio: false,
    scales: {           // axis ranges:
      y: {
        type: 'linear',
        min: 0,
        max: 255
      },
      x:{
      //  ticks:{
          type: 'time',
          time:{
            //unit:'second',
            displayFormats: {hour: 'mm:ss'}
          },
          min:0,
          max: dataSize,
          //beginAtZero: true,
          maxTicksLimit: dataSize/2
        //}
      }
    }
  }
};

谢谢

【问题讨论】:

    标签: javascript chart.js


    【解决方案1】:

    实现这一点的最简单方法是使用 chart.js 的流插件: https://nagix.github.io/chartjs-plugin-streaming/master/guide/#table-of-contents

    您会在 onRefresh 中添加数据的地方得到类似的结果。

    npm i chartjs-plugin-streaming

    import ChartStreaming from 'chartjs-plugin-streaming';
    import 'anyDatAdapterFromAhichDateLibYouAreUsing';
    
    Chart.register(ChartStreaming);
    
    const myChart = new Chart(ctx, {
      options: {
        scales: {
          x: {
            type: 'realtime',
            realtime: {
              onRefresh: function(chart) {
                chart.data.datasets.forEach(function(dataset) {
                  dataset.data.push({
                    x: Date.now(),
                    y: Math.random()
                  });
                });
              }
            }
          }
        }
      }
    });
    

    【讨论】:

    • 嗨,我正在尝试让这段代码工作,因为我认为它是正确的解决方案,但我在代码实现方面遇到了一些困难,(1) 我的 y 数据来自串行端口,所以我有set y: Number(serial.readLine()) 这是正确的吗?(2)我有数据:读数,在数据集中,我应该删除它吗?(3)在配置中我有数据:数据,我应该删除它吗?谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 2013-09-17
    • 2023-03-19
    • 2022-01-17
    相关资源
    最近更新 更多