I'm trying to update Chart JS data entirely but the old data label on the x-axis not resetting. 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.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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.