Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format Y axis of Chart.JS as Time

Tags:

chart.js

I have this chart below, I want to scale the Y axis using the TIME (the time isn't time of day it is total hours,mins, seconds so could be over 24 hours) just can't seem to get it to work, all I get is a blank screen, sure it's a syntax error but can't spot it! Thanks

var ctx = document.getElementById("myChart3").getContext('2d');
var myChart3 = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ["2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017"],
        datasets: [
            {
                label: "Time",
                backgroundColor: ["#3e95cd", "#8e5ea2", "#3cba9f", "#e8c3b9", "#c45850", "#565452", "#321456", "#129864", "#326812", "#215984"],
                data: ["11:46:07", "11:41:14", "11:55:26", "12:14:58", "11:54:55", "11:54:04", "12:28:29", "12:35:18"]
            }
  ]
    },
    options: {
        scales: {
            yAxes: [{
                type: 'time',
                time: {
                    displayFormats: {
                        minutes: 'h:mm:ss a'
                    }
                }
        }]
        }
    }
});
like image 988
Mike Todd Avatar asked May 09 '17 07:05

Mike Todd


1 Answers

Time scale works only for X axis.

It can only be placed on the X axis.

But for Y you can use a linear scale and express each time as date in milliseconds since 1970-01-01 (how the usual Date object does).

PLUNKER or use the following example:

$(function(){
  const ctx = document.getElementById('myChart').getContext('2d');
  
  let years = ["2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017"];
  let times = ["11:46:07", "11:41:14", "11:55:26", "12:14:58", "11:54:55", "11:54:04", "12:28:29", "12:35:18"];
  
  let data = years.map((year, index) => ({
    x: moment(`${year}-01-01`), 
    y: moment(`1970-02-01 ${times[index]}`).valueOf()
  }));
  
  let bckColors = ["#3e95cd", "#8e5ea2", "#3cba9f", "#e8c3b9", "#c45850", "#565452", "#321456", "#129864", "#326812", "#215984"];
  
  let myChart = new Chart(ctx, {
    type: 'line',
    data: {
        datasets: [
            {
                label: "Time",
                backgroundColor: 'rgba(188, 229, 214, 0.7)',
                pointBackgroundColor: bckColors,
                data: data,
                pointBorderWidth: 2,
                pointRadius: 5,
                pointHoverRadius: 7
            }
        ]
    },
    options: {
        scales: {
            xAxes: [
              {
                type: 'time',
                position: 'bottom',
                time: {
                  displayFormats: {
                    years: 'YYYY'
                  },
                  unit: 'year'
                }
              }
            ],
            yAxes: [
              {
                type: 'linear',
                position: 'left',
                ticks: {
                  min: moment('1970-02-01 00:00:00').valueOf(),
                  max: moment('1970-02-01 23:59:59').valueOf(),
                  stepSize: 3.6e+6,
                  beginAtZero: false,
                  callback: value => {
                    let date = moment(value);
                    if(date.diff(moment('1970-02-01 23:59:59'), 'minutes') === 0) {
                      return null;
                    }
                    
                    return date.format('h A');
                  }
                }
              }
            ]
        }
    }
  });
});
<html>  
  <head>
      <script data-require="jquery" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
      <script src="https://npmcdn.com/[email protected]"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
  </head>
  <body>
    <canvas id="myChart" width="500" height="300"></canvas>
  </body>
</html>

Explanation

You can have the years on X axis which can be a linear, time or category scale.

In this example X axis is a time scale.

The following code is used to generate values for X and Y axis:

  let data = years.map((year, index) => ({
    x: moment(`${year}-01-01`), 
    y: moment(`1970-02-01 ${times[index]}`).valueOf()
  }));

For X axis I used moment js to create a date on the first day of the corresponding year.

For Y axis I used moment js to create the date in milliseconds since 1970-01-01. In this case all hours are combined with a day to form a date. 1970-02-01 in order to prevent an edge cases that may happen for 1970-01-01. Then these milliseconds, since 1970-01-01, are used with the Y axis linear scale.

Y axis tick.callback is used to format the corresponding milliseconds to an hour. Thus using the format h A to obtain for example 1 AM, 1 PM, 12 AM, 12 PM, ....

like image 135
andreim Avatar answered Nov 09 '22 02:11

andreim