2016-09-22 141 views
1

我觉得这是一个没有记录的功能,但我承认我更有可能接受它。更改Chartjs中的Y轴单元

我有一个charjs对象:

<body> 
    <div id="container" style="width: 75%;"> 
     <canvas id="canvas"></canvas> 
    </div> 
    <script> 
    weekdays=["Monday", "Tuesday", "Wednesday", "Thurday", "Friday", "Saturday", "Sunday", "Monday"] 
    var d=new Date() 
     var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; 

     var randomScalingFactor = function() { 
      return (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100); 
     }; 

     var barChartData = { 
      labels: [weekdays[d.getDay()], weekdays[d.getDay()-6], weekdays[d.getDay()-5], weekdays[d.getDay()-4], weekdays[d.getDay()-3], weekdays[d.getDay()-2],weekdays[d.getDay()-1] ], 
      datasets: [{ 
       label: 'Logged Time', 
       backgroundColor: "rgba(220,220,220,0.5)", 
       data: sessions 
      } 
      ] 

     }; 

     window.onload = function() { 
      var ctx = document.getElementById("canvas").getContext("2d"); 
      window.myBar = new Chart(ctx, { 
       type: 'bar', 
       data: barChartData, 
       options: { 
        // Elements options apply to all of the options unless overridden in a dataset 
        // In this case, we are setting the border of each bar to be 2px wide and green 
        elements: { 
         rectangle: { 
          borderWidth: 2, 
          borderColor: 'rgb(0, 255, 0)', 
          borderSkipped: 'bottom' 
         } 
        }, 
        responsive: true, 
        title: { 
         display: true, 
         text: 'Vision Logged Hours' 
        } 
       } 
      }); 

     }; 




    </script> 

,看起来像这样:

enter image description here

我的问题是,Y轴是在几分钟内,我希望它在小时。我对功能集有点迷失 - 这可能吗?

回答

3

通过简单的手工制作的功能:

function minutesToHours(minutes) { 
    var hour = Math.floor(minutes/60); 
    minutes = minutes % 60; 
    return ((hour < 10) ? "0"+hour : hour) + ":" + ((minutes < 10) ? "0"+minutes : minutes); 
} 

然后,您可以使用yAxes的userCallback财产蜱是这样的:

options: { 
    scales: { 
     yAxes: [{ 
      ticks: { 
       userCallback: function(item) { 
        return minutesToHours(item); 
       }, 
      } 
     }] 
    } 
} 


你可以看到一个工作示例 on this fiddle,这里是它的结果:

enter image description here

0

根据官方文档,creating custom tick formats,只需简单地使用回调函数即可。

var chart = new Chart(ctx, { 
 
    type: 'line', 
 
    data: data, 
 
    options: { 
 
     scales: { 
 
      yAxes: [{ 
 
       ticks: { 
 
        // Include a dollar sign in the ticks 
 
        callback: function(value, index, values) { 
 
         return '$' + value; 
 
        } 
 
       } 
 
      }] 
 
     } 
 
    } 
 
});