如果我正确解释了您的问题,您可以使用以下选项。在直接跳到示例之前,让我解释一下方法。
首先,您的要求有点挑战性,因为这需要在 y 轴上使用“类别”刻度以及在 x 轴上使用“时间”刻度。这是一个挑战,因为折线图通常有一个“类别”、“线性”或“时间”的 x 轴和一个基于数字的刻度(例如线性、对数等)在 y 轴上。
因此,为了克服这个问题,我不得不在 y 轴上使用“线性”刻度,但使用一些回调使其看起来好像实际上是“类别”刻度。顺便说一句,我尝试在 y 轴上添加一个“类别”刻度,但永远无法渲染图表(所以我认为这是不可能的)。
由于您没有提供数据存储方式的确切示例,因此我不得不对我的模拟数据做出一些假设。不管它实际上是如何存储的,方法都是处理数据以将其转换为chart.js 可以理解的格式。在我的示例中,我使用名为 prepareDataForChart 的函数完成了此操作。
这是最终的图表配置。
var myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: "Object 1",
fill: false,
borderColor: window.chartColors.red,
backgroundColor: window.chartColors.white,
pointRadius: 0,
steppedLine: true,
data: prepareDataForChart(mockedActivityData),
}]
},
options: {
responsive: true,
title: {
display: true,
text: 'Object Activity State Over Time'
},
tooltips: {
mode: 'index',
intersect: false,
callbacks: {
// since we mapped the eventState to a numerical value,
// let's convert that back to a text value when the tooltip
// is displayed
label: function(tooltipItem, data) {
if (tooltipItem.yLabel === 1) {
return 'Normal';
} else if (tooltipItem.yLabel === 2) {
return 'Active';
}
}
}
},
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'minute',
displayFormats: {
minute: 'lll',
},
tooltipFormat: 'lll',
},
scaleLabel: {
display: true,
labelString: 'Time',
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Activity State',
},
ticks: {
min: 0,
max: 3,
stepSize: 1,
// since we mapped the eventState to a numerical value,
// let's convert that back to a text value to display
// on the y-axis (and also hide all other tick labels)
callback: function(value, index, values) {
if (value === 2) {
return 'Active';
} if (value === 1) {
return 'Normal';
} else {
return ' ';
}
},
},
}]
}
}
});
而且因为能够真正看到一些东西总是很高兴,这里是codepen example。