SmC*_*lve 2 javascript charts datetime chart.js
我正在尝试使用 Chart.js 绘制一个折线图,该图显示了一系列单圈时间的趋势,但我正在努力将时间字符串解析为正确的格式。
我有一个带有这样的单圈持续时间(分钟、秒、毫秒)的时间数组,我将其用作数据集:
const times = ["1:32.599", "1:32.300", "1:31.000"]
Run Code Online (Sandbox Code Playgroud)
在图表上绘制这些的最佳方法是什么?根据该文档chart.js之支持时间坐标轴以moment.js但它似乎并没有解析这些字符串,大概是因为它们不是日期,因为它们的持续时间,而不是在某个特定时间点。
{
type: 'line',
data: {
labels: [] // list of races,
datasets: [{
label: "Best Lap",
data: times,
}]
},
options: {
scales: {
yAxes: [{
type: 'time',
}]
}
}
}
Run Code Online (Sandbox Code Playgroud)
我感兴趣的只是比较时间,但使用 Date 对象似乎每个解决方案都令人费解。
您可以设置parser
选项以正确格式读取时间值。
yAxes: [{
type: 'time',
time: {
parser: 'm:s.SSS'
}
}]
Run Code Online (Sandbox Code Playgroud)
以下是您的示例,作为带有解析器集的片段:
yAxes: [{
type: 'time',
time: {
parser: 'm:s.SSS'
}
}]
Run Code Online (Sandbox Code Playgroud)
const times = ["1:32.599", "1:32.300", "1:31.000"];
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['1', '2', '3'], // list of races,
datasets: [{
label: "Best Lap",
fill: false,
data: times,
}]
},
options: {
scales: {
yAxes: [{
type: 'time',
time: {
parser: 'm:s.SSS',
unit: 'seconds',
unitStepSize: 5,
min: '1:0.0',
max: '2:0.0',
displayFormats: {
'seconds': 'm.s'
}
}
}]
}
}
});
Run Code Online (Sandbox Code Playgroud)
但是我注意到最小值是 y 轴的顶部,并且该reverse
选项似乎不适用于时间轴。因此,如果您更喜欢顶部的最大值,则必须在刻度回调中自己反转它。
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
<canvas id="myChart" width="200" height="200"></canvas>
Run Code Online (Sandbox Code Playgroud)
const times = ["1:32.599", "1:32.300", "1:31.000"];
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['1', '2', '3'], // list of races,
datasets: [{
label: "Best Lap",
fill: false,
data: times,
}]
},
options: {
scales: {
yAxes: [{
type: 'time',
time: {
parser: 'm:s.SSS',
unit: 'seconds',
unitStepSize: 5,
min: '1:0.0',
max: '2:0.0',
displayFormats: {
'seconds': 'm.s'
}
},
ticks: {
callback: function(value, index, values) {
//Ticks reverse does not work with time axes so we have to revert in this callback
if (values[values.length - index] != undefined) {
return moment(values[values.length - index].value).format('m.ss');
}
}
}
}]
}
}
});
Run Code Online (Sandbox Code Playgroud)