[Chartjs]-Chartjs Custom Legend with Time on Y-axis

3👍

Have a try like this,

Need to modify your data structure a little and set the y=axis properties for displaying the required label format.

P.S : you need to use the latest chart.js library since the position right functionality was recently added and also i have increased the second value in your given example to display some meaningful data in hh:mm format.

function formatTime(secs)
{
    var hours = Math.floor(secs / (60 * 60));
   
    var divisor_for_minutes = secs % (60 * 60);
    var minutes = Math.floor(divisor_for_minutes / 60);
 
    var divisor_for_seconds = divisor_for_minutes % 60;
    var seconds = Math.ceil(divisor_for_seconds);
  
    return hours + ":" + minutes;
}


var ctx = document.getElementById("myChart");


var myChart = new Chart(ctx, {
type: 'bar',
animation: false,
data: {
    labels: ["Time"],
    datasets: [{
        label: "Service A", 
        data: [1800], 
        backgroundColor: '#0073CF',
        borderColor: '#fff',
        borderWidth: 2 
    },
    {
        label: "Service B",
        data: [36000],
        backgroundColor: '#FF0000',
        borderColor: '#fff',
        borderWidth: 2 
    },
    {
        label: "Service C",
        data: [8000],
        backgroundColor: '#7DC24B',
        borderColor: '#fff',
        borderWidth: 2 
    }]
},
options: {
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero:true,
                callback: function(label, index, labels) {
                 return formatTime(label);
                 }
            }
        }]
    },
    legend: {
            position: "right",
            display:true
      
        }
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
<div style="width: 400px; height: 400px;">
 <canvas name="myChart" id="myChart" width="400px" height="400px"> </canvas>
 </div>

Leave a comment