我想在水平条形图中显示持续时间。我发现我需要moment.js所以格式hh:mm可以使用,但我不能让水平栏工作。我试图从How to feed hour and minute data into chartJS复制代码并将其更改为我想要的但不起作用。
代码:
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 => moment(e.x, 'HH:mm'));
var data = result.map(e => +e.y);
var ctx = document.getElementById("MeSeStatusCanvas").getContext('2d');
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: labels,
datasets: [{
label: 'Voltage Fluctuation',
data: data,
borderWidth: 1
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'hour',
displayFormats: {
hour: 'HH:mm'
}
}
}]
},
}
});
有人可以帮帮我吗?
提前致谢
答案 0 :(得分:1)
<强>ꜰɪʀꜱᴛ强>
解析标签和数据,如下所示:
var labels = result.map(e => e.y);
var data = result.map(e => moment(e.x, 'HH:mm'));
<强>ꜱᴇᴄᴏɴᴅ强>
使用 yLabels
属性而不是labels
(在data
对象内),因此:
...
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>