Chartjs-How to configure linear labels in Time Cartesian Chartjs?

0👍

Two small changes will achieve the desired result:

  • set stepSize: 2 to ‘show labels on X axis every 2 hours (0h, 2h, 4h…)’
  • remove ticks: { source: 'data' } as that:

    generates ticks from data (including labels from data {t|x|y} objects)”

Here’s a working example based on the posted code:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    //labels: ['0h', '2h', '4h', '6h', '8h', '10h', '12h', '14h', '16h', '18h', '20h', '22h', '0h'],
    datasets: [{
      label: 'AAA1111',
      //xAxisID: 'Hora',
      //yAxisID: 'Velocidade',
      data: [{
          t: new Date("2015-3-15 12:30"),
          y: 12
        },
        {
          t: new Date("2015-3-15 14:40"),
          y: 45
        },
        {
          t: new Date("2015-3-15 17:50"),
          y: 77
        }
      ],
      borderColor: 'rgba(255, 0, 0, 1)',
      borderWidth: 4,
      fill: false,
      lineTension: 0,
      lineJoint: "round",
      spanGaps: true
    }]
  },
  options: {
    scales: {
      xAxes: [{
        type: 'time',
        distribution: 'linear',
        time: {
          unit: 'hour',
          stepSize: 2
        }
      }]
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.bundle.min.js"></script>
<canvas id="myChart"></canvas>

Leave a comment