Chartjs-Time chart labels with some X axis labels using Chart js v3

1๐Ÿ‘

As per the docs, the labels property is optional. The easy answer is just not to use it. You can always use the {x,y} or {t,y} formats, which will build the labels on the fly. Alternately, you just need to make sure that the number of labels matches the size of the larger dataset, whichever that is.

1๐Ÿ‘

As Samuei pointed out if you have multiple datasets of different length the best way to specify is with the object notation as you did in your edit, in case the keys are different you can also specify the parsing keys at dataset level instead of in the options.

The reason why your chart still isnt showing is that since chart.js v3 you will need to use a date adapter for time axis, chart.js currently has 3 date adapters available (https://github.com/chartjs/awesome#adapters) I used the moment one for this example:

var chart = new Chart(document.getElementById('sensorValuesChart'), {
  type: 'line',
  data: {
    datasets: [{
      label: 'My First dataset',
      //backgroundColor: 'rgb(255, 99, 132)',
      borderColor: 'rgb(255, 99, 132)',
      data: [{
        value: "65",
        time: "2021-05-19 09:13:41"
      }, {
        value: "70",
        time: "2021-05-19 09:09:39"
      }],
    }]
  },
  options: {
    parsing: {
      xAxisKey: 'time',
      yAxisKey: 'value'
    },
    scales: {
      x: {
        type: 'time',
        display: true,
        time: {
          unit: 'minute',
          displayFormats: {
            hour: "DD/MM | HH:mm"
          },

        },
      },
      y: {
        type: 'linear'
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@0.1.1"></script>

<canvas id="sensorValuesChart"></canvas>

Leave a comment