[Chartjs]-Line Chart using Chart js with time data

1đź‘Ť

Although I didn’t manage to use a time axis for both the x- and y-axes, I managed to create a workaround with a timed x-axis and a linear y-axis.
I parse your time and return the time in seconds (integer). I use this value to display your time and change the format back to mm:ss.
I hope this is what you wanted. I’m not sure you want the axes this way (because in your code you use the y-axis as type “time”).

PS: My first post, please feel free to tell me what I can improve.

JSFiddle: https://jsfiddle.net/5837nmyo/

JSBin: https://jsbin.com/yadixolica/1/edit?html,js,output

let sData = {}
sData.label = ["08-Aug-2019","11-Aug-2019","22-Aug-2019","25-Aug-2019"]
sData.time = ["1:08","1:44","2:27","1:02"]

let chartData = {}
chartData.label = sData.label
chartData.time = parseTimeToSeconds(sData.time)

function parseTimeToSeconds(times){
  let regex = /(\d*):(\d{2})/gm
  let parsedTime = []

  for (let x = 0; x < times.length; x++) {
    let match = regex.exec(times)
    parsedTime.push(parseInt(match[1])*60 + parseInt(match[2]))
  }
  return parsedTime
}

let time_ctx = document.getElementById('time_chart');

let time_data = {
  labels: chartData.label,
  datasets: [{
    label: chartData.label,
    data: chartData.time
  }]
};

let time_options = {
  responsive: true,
  title: {
    display: false
  },
  legend: {
    display: false
  },
  tooltips: {
    callbacks: {
      label: function(tooltipItem, data){
        let value = parseInt(tooltipItem.value)
        if (value%60 < 10)
          return Math.floor(value/60) + ":" + 0 + value%60
        else
          return Math.floor(value/60) + ":" + value%60
      }
    }
  },
  scales: {
    xAxes: [{
      type: 'time'
    }],
    yAxes: [{
      ticks: {
        min: 0,
        max: 1800,
        stepSize: 120,
        callback: function(value, index, values) {
          if (value%60 < 10)
            return Math.floor(value/60) + ":" + 0 + value%60
          else 
            return Math.floor(value/60) + ":" + value%60
        }
      }      
    }]
  }
};

let chart2 = new Chart(time_ctx, {
  type: "line",
  data: time_data,
  options: time_options
});

Leave a comment