我有一些基于时间的数据,我想要图形表示,并希望使用 Chartjs 来绘制它。
数据如下所示:
Time State
--------------
7am up
9am down
10.45am out
17.35 up
另外,每个“状态”都有自己的颜色,所以在使用条形图时我会使用它作为条形颜色
up = red
down = yellow
out = green
我追求的最终结果是一个简单的单行栏,如下所示......
我想我可以使用 Chartjshorizontal stacked
条形图(https://www.chartjs.org/docs/latest/charts/bar.html#horizontal-bar-chart https://www.chartjs.org/docs/latest/charts/bar.html#horizontal-bar-chart)以某种方式做到这一点,但我就是不知道如何让它工作。
一些(不工作)实验代码如下:
private createChart(): void {
if (this.chart !== undefined) {
return;
}
Chart.register(BarController, PointElement, Tooltip, Legend, TimeScale, LinearScale, CategoryScale, LinearScale, BarElement);
const options: ChartOptions = {
plugins: {
legend: {
display: false,
},
title: {
display: false,
},
},
indexAxis: 'y',
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
stacked: true,
type: 'time',
display: true,
// position: 'bottom',
time: {
unit: 'minute',
displayFormats: {
minute: 'h:mm a'
}
}
},
x: {
stacked: false,
}
}
};
this.chart = new Chart(this.canvasRef.nativeElement, {
type: 'bar',
data: this.chartData,
options
});
this.chart.config.options.scales.y.min = new Date('2023-02-13T06:19:31.842Z').getTime();
const labels = [
'up',
'down'
// 'Dataset 2'
];
const d1 = new Date('2023-02-13T06:20:32.842Z').getTime();
const d2 = new Date('2023-02-13T06:21:33.842Z').getTime();
this.chartData = {
labels,
datasets: [{
label: 'up',
data: [{x: 10, y: d1}],
backgroundColor: 'red',
},
{
label: 'down',
data: [{x: 20, y: d2}],
backgroundColor: 'green',
}
]
};
this.chart.update();
}
在上面我尝试了标签、x 值、y 值、数据形状的各种组合,但我什至只得到一个空图。
也许这实际上是不可能的(我试图使用错误的组件)。
我怎样才能使用chartjs实现这一点?
Update
使用下面@winner_joiner 的示例,我已将其副本放在并尝试在 x 轴上使用时间,但可以看到它仍然没有使用日期作为长度来绘制条形