chart.js中的hh:mm在X轴上,文本标签在Y轴上 [英] hh:mm in chart.js on X-axis and text labels on the Y-axis
本文介绍了chart.js中的hh:mm在X轴上,文本标签在Y轴上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在水平条形图中显示持续时间.我发现我需要moment.js,因此可以使用hh:mm格式,但是我无法使horizontalbar正常工作.我试图从>如何输入小时和分钟的代码中复制代码数据导入chartJS 并将其更改为我想要的方式,但这不起作用.
I want to show duration time in a horizontal bar chart. I found out that I need moment.js so the format hh:mm can be used but I cant get the horizontalbar to work. I ve tried to copy the code from How to feed hour and minute data into chartJS and change it to how I want it but that doesn't work.
代码:
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'
}
}
}]
},
}
});
有人可以帮我吗?
预先感谢
推荐答案
ꜰɪʀꜱᴛ
按如下方式解析标签和数据:
parse the labels and data as follows :
var labels = result.map(e => e.y);
var data = result.map(e => moment(e.x, 'HH:mm'));
ꜱᴇᴄᴏɴᴅ
使用 yLabels
属性代替labels
(在data
对象内部),例如:
use yLabels
property instead of labels
(inside data
object), as such :
...
data: {
yLabels: labels,
...
ᴡᴏʀᴋɪɴɢᴇxᴀᴍᴘʟᴇstrong
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>
这篇关于chart.js中的hh:mm在X轴上,文本标签在Y轴上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文