Chartjs-Timeline on Y axis, with chart.js

1πŸ‘

βœ…

I’d use values in seconds for Y-axis.

function timeToSeconds(time) {
  var parts = time.split(":");
  var valueInSeconds = 0;
  var secondsInTimeUnit = [3600, 60, 1];
  for (j = 0; j < parts.length; j++) {
    valueInSeconds = valueInSeconds + secondsInTimeUnit[j] * parseInt(parts[j]);
  }
  return valueInSeconds;
}

than in your code:

function getChartDataPiece(name) { 
//.....
            var time = [];           
            var operator = [];                    

            for (i = 0; i <  response.pieces.length; i++) {
                time.push(timeToSeconds(response.pieces[i].time));              
                operator.push(response.pieces[i].name);                                
            }       

Demo

However the Y axis values are in seconds.

Here and here some tips how to change it. Don’t forget to upvote these two;)

Here is what you need to change:

function renderChartPiece(operator, time) {
//...
        options: {
            scales: {
                yAxes: [{
//...
                   ticks: {
                     beginAtZero:true,
                     stepSize: 30, //step every 30 seconds
                     callback: function(label, index, labels) {
                       if (parseInt(label) % 30 == 0) {
                         //convert seconds to mm:ss format
                         var mins = parseInt(parseInt(label)/60);
                         var seconds = parseInt(label) - mins*60;
                         return mins+":"+(seconds < 10 ? "0" : "") +seconds;
                       } else {
                         return "";
                       }
                     }
                   },

And here is final solution


EDIT 2020/04/18:

Tooltip values in previous solution had values is seconds.

You can find more here

  //...
  options: {

        //add this for tooltips
        tooltips: {
            callbacks: {
                label: function(tooltipItem, data) {
                    var label = data.datasets[tooltipItem.datasetIndex].label || '';
                    if (label) {
                        label += ': ';
                    }
                  var mins = parseInt(parseInt(tooltipItem.yLabel)/60);
                  var seconds = parseInt(tooltipItem.yLabel) - mins*60;
                  mins =  mins+":"+(seconds < 10 ? "0" : "") +seconds;                  
                  return label + mins;
                }
            }
        },
        scales: {
        //....

Corrected version here

Leave a comment