Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to feed hour and minute data into chartJS

I'm trying to make a line chart using Chart.js. My data is of the form:

var result = [{x:"18:00",y:"230"},{x:"19:00",y:"232"},{x:"20:00",y:"236"},{x:"22:00",y:"228"}];

Where x represents the time with hours and minutes. I fed the data like this

var ctx = document.getElementById("myChart").getContext('2d');
    var myChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ["00:00","01:00","02:00","03:00","04:00","05:00","06:00","07:00","08:00","09:00","10:00","11:00","12:00","13:00","14:00","15:00","16:00","17:00","18:00","19:00","20:00","21:00","22:00","23:00","24:00"],
            datasets: [{
                label: 'Voltage Fluctuation',
                data: result,
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                xAxes: [{
                    type: 'time',
                    position: 'bottom',
                    unit: 'minute',
        time: {
          displayFormats: {
            hour: 'HH:mm'
          }
        }
      }],
    },
  }
});

And I'm getting an empty chart. Where am I going wrong? I feel I'm doing something wrong with my labels since they don't show up on the chart but I don't understand how. Is there any way I can feed datalabels with momentjs?

like image 509
Saikiran Avatar asked Dec 19 '22 04:12

Saikiran


1 Answers

You cannot just pass the result array to data, as it isn't in correct format. data property expects an array of numbers. So, you need to parse the labels (using moment.js) and data from result array before using them for the chart.

Here is how labels and data should be parsed from the result array and fed to the chart :

var result = [{ x: "18:00", y: "230" }, { x: "19:00", y: "232" }, { x: "20:00", y: "236" }, { x: "22:00", y: "228" }];

// parse labels and data
var labels = result.map(e => moment(e.x, 'HH:mm'));
var data = result.map(e => +e.y);

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: labels,
      datasets: [{
         label: 'Voltage Fluctuation',
         data: data,
         borderWidth: 1
      }]
   },
   options: {
      scales: {
         xAxes: [{
            type: 'time',
            time: {
               unit: 'hour',
               displayFormats: {
                  hour: 'HH:mm'
               }
            }
         }]
      },
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="myChart"></canvas>
like image 97
ɢʀᴜɴᴛ Avatar answered Dec 24 '22 00:12

ɢʀᴜɴᴛ