我有这两个数据集:
是否可以在一个图表中显示这两行,但第二行尊重第 1 行的时间戳)?当我阅读文档时,其中写道所有数据集都应具有相同数量的标签,但后来我遇到了一些可能满足我要求的解决方案。但这些解决方案似乎适用于以前版本的 Chart.js,不再有效。
Or 是修改数据集 2) 为数据集 1) 中每个点插入值的唯一解决方案 非常感谢
这是代码:
let labels = []
let date = new Date();
date.setDate(date.getDate() - 10);
const tenDays = [];
for (let i = 0; i < 10; i++) {
const dateToDisplay = date.setDate(date.getDate() + 1);
labels.push(new Date(dateToDisplay).toISOString());
//array of 10 days in history from now
tenDays.push({
time: dateToDisplay,
value: Math.floor(Math.random() * 10)
})
}
date = new Date();
date.setDate(date.getDate() - 10);
//array of only three days, in tenDays array that is 1st, 5th and 10th day
const threeDays = [
{time: date, value: 6 },
{time: date.setDate(date.getDate() + 5), value: 4 },
{time: date.setDate(date.getDate() + 5), value: 5 },
];
var dataset1 = {
label: 'dataset1',
data: tenDays.map(data => data.value)
}
var dataset2 = {
label: 'dataset2',
data: threeDays.map(data => data.value)
}
//create Chart
new Chart(document.querySelector('#chart') as HTMLCanvasElement, {
type: 'line',
data: {
labels: labels,
datasets: [dataset1, dataset2],
},
options: {
responsive: true,
maintainAspectRatio: false,
},
});
如果您有两个数据集的实际时间,您可以使用它们将点放置在 x 轴上。所以你可以:
然后,每个点都被放置在正确的时间、定义的位置,一切就位。这是经过这些更改的代码的简化版本:
let date = new Date();
date.setDate(date.getDate() - 10);
const tenDays = [];
for (let i = 0; i < 10; i++) {
const dateToDisplay = date.setDate(date.getDate() + 1);
//array of 10 days in history from now
tenDays.push({
time: dateToDisplay,
value: Math.floor(Math.random() * 10)
})
}
date = new Date();
date.setDate(date.getDate() - 10);
//array of only three days, in tenDays array that is 1st, 5th and 10th day
const threeDays = [{
time: date.setDate(date.getDate() + 1),
value: 6
},
{
time: date.setDate(date.getDate() + 4),
value: 4
},
{
time: date.setDate(date.getDate() + 5),
value: 5
},
];
//create Chart
new Chart(document.querySelector('#chart'), {
type: 'line',
data: {
datasets: [{
data: tenDays,
label: "many"
},
{
data: threeDays,
label: "few"
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
parsing: {
xAxisKey: "time",
yAxisKey: "value",
},
scales: {
x: {
type: "time",
time: {
unit: "day"
}
}
}
},
});
<div style="min-height:300px">
<canvas id="chart"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
我不确定这是否是您想要的,您是否有两个数据集的实际时间/