我正在尝试绘制一些信息,而我的x-axis
是时间。为此,我正在使用chart.js
和moment.js
,但在将这段时间转换为标签时遇到一些问题。
我的代码是:
var sData = {
datasets: [{
label: 'Dataset1',
data: [{ x: '09:00', y: 88 }, { x: '09:10', y: 89 }, { x: '09:13', y: 86 }, { x: '09:23', y: 86 },
{ x: '09:26', y: 85}, { x: '09:29', y: 83 }]
}, {
label: 'Dataset2',
data: [{ x: '09:02', y: 88 }, { x: '09:13', y: 89 }, { x: '09:14', y: 86 }, { x: '09:20', y: 86 },
{ x: '09:24', y: 85 }, { x: '09:29', y: 83 }]
}]
}
sData.datasets[0].data = formatData(sData.datasets[0].data)
sData.datasets[1].data = formatData(sData.datasets[1].data)
function formatData(oldData) {
var newData = []
for (var i = 0; i < oldData.length; i++) {
var currentData = {}
currentData.x = moment(oldData[i].x, "HH:mm").format('HH:mm')
currentData.y = oldData[i].y
newData.push(currentData)
}
return newData
}
var data = sData
var options = {
responsive: true,
scales: {
xAxes: [{
type: 'time',
}]
},
tooltips: {
callbacks: {
title: function(tooltipItem, data){
return moment(tooltipItem[0].label).format('HH:mm')
}
}
}
}
var ctx = document.getElementById('bateria_graf');
let chart = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
我认为问题是我没有正确格式化时间,但是我不知道如何解决。有人可以帮我吗?
非常感谢!
问题出在您的formatData
功能中。使用moment
,您可以正确解析时间,然后将format
还原为原始string
值。解决方案是摆脱调用format
的麻烦。
currentData.x = moment(oldData[i].x, "HH:mm");
var sData = {
datasets: [{
label: 'Dataset1',
data: [{ x: '09:00', y: 88 }, { x: '09:10', y: 89 }, { x: '09:13', y: 86 }, { x: '09:23', y: 86 },
{ x: '09:26', y: 85}, { x: '09:29', y: 83 }]
}, {
label: 'Dataset2',
data: [{ x: '09:02', y: 88 }, { x: '09:13', y: 89 }, { x: '09:14', y: 86 }, { x: '09:20', y: 86 },
{ x: '09:24', y: 85 }, { x: '09:29', y: 83 }]
}]
}
sData.datasets[0].data = formatData(sData.datasets[0].data)
sData.datasets[1].data = formatData(sData.datasets[1].data)
function formatData(oldData) {
var newData = []
for (var i = 0; i < oldData.length; i++) {
var currentData = {}
currentData.x = moment(oldData[i].x, "HH:mm")
currentData.y = oldData[i].y
newData.push(currentData)
}
return newData
}
var options = {
responsive: true,
scales: {
xAxes: [{
type: 'time',
}]
},
tooltips: {
callbacks: {
title: (tooltipItem, data) => moment(tooltipItem[0].label).format('HH:mm')
}
}
}
var ctx = document.getElementById('bateria_graf').getContext('2d');
let chart = new Chart(ctx, {
type: 'line',
data: sData,
options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.1.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="bateria_graf"></canvas>