Chartjs-How to put labels at 4 points of the day?

0👍

Took me some time, but I think I got the answer.

You can define the ticks with and display them with options.scales.xAxes[0].ticks.source = 'labels', but the hardest part was to get the next timestamp of 0:00, 6:00, 12:00 or 18:00.
That’s why the code for the first label is quite complex. If you want to know anything, just let me know and I can explain it.

Should work with any time you want.

Complete code (same as JSBin with preview here):

let data = {
  datasets: [{
    label: 'CHRT - Chart.js Corporation',
    backgroundColor: 'red',
    borderColor: 'red',
    type: 'line',
    pointRadius: 0,
    pointHoverRadius: 0,
    fill: false,
    lineTension: 0,
    borderWidth: 2,
    data: []
  }]
}

function randomNumber(min, max) {
  return Math.round(Math.random() * (max - min) + min)
}

// temp variable for data.datasets[0].data
let datasetData = []

// Fill first dataset
datasetData[0] = {
  x: moment("2000-01-01T08:30"),
  y: randomNumber(0, 100)
}

// Fill remaining datasets
for (let i = 1; i < 48; i++) {
  datasetData[i] = {
    x: moment(datasetData[i-1].x).add(30, 'minutes'),
    y: randomNumber(0, 100)
  }
}

data.datasets[0].data = datasetData

// Fill first label
data.labels = [
  moment(datasetData[0].x).hour(moment(datasetData[0].x).hour() + (6 - moment(datasetData[0].x).hour() % 6) % 6).minutes(0)
]

// Fill remaining labels
for (let i = 1; i < 4; i++) {
  data.labels.push(moment(data.labels[i-1]).add(6, 'hours'))
}

let options = {
  responsive: true,
  scales: {
    xAxes: [{
      type: 'time',
      time: {
        unit: 'hour',
        displayFormats: {
          hour: 'kk:mm'
        }
      },
      ticks: {
        source: 'labels'
      }
    }],
    yAxes: [{
      gridLines: {
        drawBorder: false
      }
    }]
  },
  tooltips: {
    intersect: false,
    mode: 'index',
    callbacks: {
      title: function(tooltipItem, data) {
        return moment(tooltipItem[0].label).format('YYYY-MM-DD, HH:mm')
      }
    }
  }
}

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

Leave a comment