[英]Chart JS: Old chart data not clearing
I'm trying to update Chart JS data entirely but the old data label on the x-axis not resetting.我正在尝试完全更新 Chart JS 数据,但 x 轴上的旧数据 label 未重置。 Is there anything wrong with my code?
我的代码有什么问题吗?
let netProfitData = @this.netProfitData;
netProfitChart.data.datasets[0].data = netProfitData;
console.log(netProfitChart.data.datasets);
netProfitChart.data.datasets[0].backgroundColor = netProfitData.map((value) =>
value.y > 0 ? fullConfig.theme.colors.green[400] : fullConfig.theme.colors.red[400]);
netProfitChart.update();
Data array in datasets seems correct to me.数据集中的数据数组对我来说似乎是正确的。
This is because internally chart.js still populates the labels array so you will need to clear that one before replacing your data:这是因为在内部 chart.js 仍然填充标签数组,因此您需要在替换数据之前清除该数组:
chart.data.labels = [];
chart.data.datasets[0].data = newData;
chart.update();
const options = { type: 'line', data: { datasets: [{ label: '# of Votes', data: [{ x: 'hi', y: 5 }, { x: 'test', y: 10 }, { x: 'end', y: 2 }], borderColor: 'pink' }] }, options: {} } const ctx = document.getElementById('chartJSContainer').getContext('2d'); const chart = new Chart(ctx, options); chart.data.labels = []; chart.data.datasets[0].data = [{ x: 'k', y: 1 }, { x: 't', y: 4 }, { x: 'a', y: 5 }]; chart.update();
<body> <canvas id="chartJSContainer" width="600" height="400"></canvas> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script> </body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.