Chartjs-ChartJs xAxis incorrect order on auto update

0👍

Instead of formatting the date/time yourself, define the x axis as a Time Cartesian Axis and use one of the available Chart.js date adapters.

Please take a look at your amended and runnable code and see how it works with the Luxon adapter.

let chart = new Chart('chart', {
  type: "line",
  data: {
    datasets: [
      {
        yAxisID: "yAxis1",
        label: "a",
        data: [],
        borderWidth: 1,
        spanGaps: true,
        tension: 0
      },
      {
        yAxisID: "yAxis2",
        label: "b",
        data: [],
        borderWidth: 1,
        spanGaps: true,
        tension: 0
      }
    ]
  },
  options: {
    scales: {
      x: {
        type: 'time',
          time: {       
            unit: 'second',              
            displayFormats: {
              second: 'yyyy-MM-dd HH:mm:ss',
            },
            tooltipFormat: 'yyyy-MM-dd HH:mm:ss' 
        },
        ticks: {
          maxRotation: 90,
          minRotation: 45
        }
      },
      yAxis1: {
        type: "linear",
        display: true,
        position: "left"
      },
      yAxis2: {
        type: "linear",
        display: true,
        position: "right",
        grid: {
          drawOnChartArea: false
        }
      }
    }
  }
});

setInterval(() => {
  chart.data.datasets.forEach((d) => {
    d.data.push({ x: new Date(), y: Math.floor(Math.random() * 10) });
  });
  chart.update();
}, 2000);
<script src="https://cdn.jsdelivr.net/npm/chart.js@^4"></script>
<script src="https://cdn.jsdelivr.net/npm/luxon@^3"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon@^1"></script>
<canvas id="chart"></canvas>

Leave a comment