Chartjs-Hh:mm in chart.js on X-axis and text labels on the Y-axis

1👍

ꜰɪʀꜱᴛ

parse the labels and data as follows :

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

ꜱᴇᴄᴏɴᴅ

use yLabels property instead of labels (inside data object), as such :

...
data: {
      yLabels: labels,
      ...

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩

var result = [{ x: "150:00", y: "bar 1" }, { x: "19:00", y: "bar 2" }, { x: "20:00", y: "bar 3" }, { x: "22:00", y: "bar 4" }];

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

var ctx = document.getElementById("MeSeStatusCanvas").getContext('2d');
var myChart = new Chart(ctx, {
   type: 'horizontalBar',
   data: {
      yLabels: labels,
      datasets: [{
         label: 'Voltage Fluctuation',
         data: data,
         borderWidth: 1
      }]
   },
   options: {
      scales: {
         xAxes: [{
            type: 'time',
            time: {
               unit: 'hour',
               displayFormats: {
                  hour: 'HH:mm'
               },
               /* (required to show first bar)
               	set min prop, less than the minimum value of data.
               	in this case minimum data value is '15:00', so we set '14:00'
                */
               min: moment('14:00', '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.7.0/Chart.min.js"></script>
<canvas id="MeSeStatusCanvas"></canvas>

Leave a comment