Chartjs-How can I control the number of values shown on a data logger using chart.js?

0👍

You messed some stuff with the x labels. There are 2 options, either keep the first label as 0 (or 1), and the other option is to increase it so after 20 it’s 21 and so on.

So either use true or false here:

for (var i = 0; i < 20; i++) {
    labels[i] = false ? i : pos + i;
}
document.addEventListener('DOMContentLoaded', function() {
  const ctx = document.getElementById('chartCanvas').getContext('2d');

  const data = {
    labels: [],
    datasets: [{
      label: 'Value',
      data: [],
      borderColor: 'blue',
      backgroundColor: 'rgba(0, 0, 255, 0.1)',
    }]
  };

  const options = {
    title: {
      display: true,
      text: 'Live Data Logger',
    },
    legend: {
      position: 'bottom',
    },
    scales: {
      x: {
        type: 'linear',
        position: 'bottom',
        ticks: {
          stepSize: 1,
          suggestedMin: 0,
        }
      },
      y: {
        beginAtZero: true,
      }
    },
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      zoom: {
        zoom: {
          wheel: {
            enabled: true,
          },
          drag: {
            enabled: true,
          },
          mode: 'xy',
        },
        pan: {
          enabled: false,
          mode: 'x',
        }
      }
    }
  };

  const chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: options,
  });


  var pos = 0;
  const window_size = 20;

  function addDataPoint() {
    const x = chart.data.labels.length;
    const y = Math.random() * 100;
    pos++;

    var labels = chart.data.labels
    var data = chart.data.datasets[0].data

    labels.push(x);
    data.push(y);

    if (data.length >= window_size) {
      labels.shift();
      data.shift();
    }

    // renumerate, or change pos (use true or false)
    for (var i = 0; i < window_size; i++) {
      labels[i] = false ? i : pos + i;
    }

    chart.data.labels = labels
    chart.data.datasets[0].data = data

    chart.update();

  }

  setInterval(addDataPoint, 250)

  const resetZoomButton = document.getElementById('resetZoomButton');
  resetZoomButton.addEventListener('click', function() {
    chart.resetZoom();
  });

});
<!DOCTYPE html>
<html>

<head>
  <title>Test Chart</title>
</head>

<body>
  <div style="position: relative;">
    <canvas id="chartCanvas" width="600" height="200"></canvas>
    <button id="resetZoomButton" style="position: absolute; top: 10px; right: 10px;">Reset Zoom</button>
  </div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.3.1/chart.umd.min.js" integrity="sha512-UcCmTcAm3IkzrswF+WqvwWSjsnv8nsJpDL09KHCETWS0g0WjoIZDRUYXCeHeow1cEij0kqL9OwRwirv/xCQ6GA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

</body>

</html>

Leave a comment