我是一个完全的新手工作的数据记录器-和惊喜:我有麻烦了。我的想法是始终在chart.js图上显示一定数量的值(现在假设为20个)。基本上,这意味着我需要隐藏最旧的数据点,并在右侧追加最新的数据点。我当前的代码如下所示:
<!DOCTYPE html>
<html>
<head>
<title>Test Chart</title>
</head>
<body>
<div style="position: relative;">
<canvas id="chartCanvas" width="600" height="400"></canvas>
<button id="resetZoomButton" style="position: absolute; top: 10px; right: 10px;">Reset Zoom</button>
</div>
<script src="/node_modules/chart.js/dist/chart.umd.js"></script>
<script src="/node_modules/hammerjs/hammer.min.js"></script>
<script src="/node_modules/chartjs-plugin-zoom/dist/chartjs-plugin-zoom.min.js"></script>
<script src="main.js"></script>
</body>
</html>
字符串
main.js:
document.addEventListener('DOMContentLoaded', function () {
const ctx = document.getElementById('chartCanvas').getContext('2d');
const data = {
labels: [],
datasets: [{
label: 'Value',
data: [],
borderColor: 'blue',
backgroundColor: 'rgba(0, 0, 255, 0.1)',
}]
};
const options = {
title: {
display: true,
text: 'Live Data Logger',
},
legend: {
position: 'bottom',
},
scales: {
x: {
type: 'linear',
position: 'bottom',
ticks: {
stepSize: 1,
suggestedMin: 0,
}
},
y: {
beginAtZero: true,
}
},
responsive: true,
maintainAspectRatio: false,
plugins: {
zoom: {
zoom: {
wheel: {
enabled: true,
},
drag: {
enabled: true,
},
mode: 'xy',
},
pan: {
enabled: false,
mode: 'x',
}
}
}
};
const chart = new Chart(ctx, {
type: 'line',
data: data,
options: options,
});
function addDataPoint() {
const x = chart.data.labels.length;
const y = Math.random() * 100;
chart.data.labels.push(x);
chart.data.datasets[0].data.push(y);
chart.update();
}
setInterval(addDataPoint, 1000)
const resetZoomButton = document.getElementById('resetZoomButton');
resetZoomButton.addEventListener('click', function () {
chart.resetZoom();
});
});
型
我已经尝试将addDataPoint()函数修改为类似的形式
function addDataPoint() {
const x = chart.data.labels.length;
const y = Math.random() * 100;
if (x<20){
chart.data.labels.push(x);
chart.data.datasets[0].data.push(y);
chart.update();
} else {
chart.data.labels.shift();
chart.data.datasets[0].data.shift();
chart.update();
}
}
型
但是,它似乎只是删除了旧值,并在同一个地方追加了所有新值。我该如何解决这个问题?
此外,我还想这样做,以便旧值不会被删除,而只是隐藏起来,这样,如果我缩小,我仍然可以看到旧值。(我已经使用插件添加了缩放功能)
谢谢你的帮助!
更新:我现在可以控制显示的数字数量在20,然而,旧的数据将被删除-不是我想要的。有什么办法解决这个问题吗?
1条答案
按热度按时间bwitn5fc1#
你把一些东西和x标签搞混了。有两个选项,要么保持第一个标签为
0
(或1
),另一个选项是增加它,以便在20
之后是21
等等。所以在这里使用
true
或false
:字符串
的数据