我正在使用chart.js创建一个非常简单的图表,并坚持使用两个小问题。
以下是我用来创建图表/图表的代码
<div style="width: 400px; height: 400px;">
<canvas name="myChart" id="myChart" width="400px" height="400px"> </canvas>
</div>
<script>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
animation: false,
data: {
labels: ["Service A", "Service B", "Service C"],
datasets: [{
label: 'Time In Service',
data: [180, 360, 180],
backgroundColor: [
'#0073CF',
'#FF0000',
'#7DC24B'
],
borderColor: [
'#fff',
'#fff',
'#fff'
],
borderWidth: 2
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
此处可以看到当前图表Chart Generated 什么是需要像Chart Needed
任何一点帮助将不胜感激。
答案 0 :(得分:1)
尝试这样,
需要稍微修改数据结构并设置y = axis属性以显示所需的标签格式。
P.S:您需要使用最新的chart.js库,因为最近添加了位置权限功能,并且我已经增加了给定示例中的第二个值,以hh:mm格式显示一些有意义的数据。
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
}
}
});
&#13;
<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>
&#13;