【发布时间】:2023-02-13 17:31:23
【问题描述】:
我有一些基于时间的数据,我想要一个图形表示,并希望我可以使用 Chartjs 来绘制它。
数据如下所示
Time State
--------------
7am up
9am down
10.45am out
17.35 up
此外,每个“状态”都有自己的颜色,因此在使用条形图时我会将其用作条形颜色
up = red
down = yellow
out = green
我所追求的最终结果是一个简单的单行栏,如下所示......
我想我可以使用 Chartjs horizontal stacked 条形图 (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 实现这一点有一些指示吗?
【问题讨论】:
标签: chart.js