I cannot debug the following code. I would like to update chart data (not add on top; delete current data and add completely new dataset). (Not)Working example on codepen:
https://codepen.io/anon/pen/bvBxpr
var config = { type: 'line', data: { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [{ label: "My First dataset", data: [65, 0, 80, 81, 56, 85, 40], fill: false }] } }; var ctx = document.getElementById("myChart").getContext("2d"); var myChart = new Chart(ctx, config); labelsNew = ["Why", "u", "no", "work", "???"]; dataNew = [2, 4, 5, 6, 10]; function updateData(chart, label, data) { removeData(); chart.data.labels.push(label); chart.data.datasets.forEach((dataset) => { dataset.data.push(data); }); chart.update(); }; function removeData(chart) { chart.data.labels.pop(); chart.data.datasets.forEach((dataset) => { dataset.data.pop(); }); chart.update(); } $('.button-container').on('click', 'button', updateData(myChart, labelsNew, dataNew));
Advertisement
Answer
I figured it out. This works:
function addData(chart, label, data) { chart.data.labels = label chart.data.datasets.forEach((dataset) => { dataset.data = data; }); chart.update(); } $("#btn").click(function() { addData (myChart, labelsNew, dataNew); });
instead of pushing the data (which adds on), data needs to be allocated by ” = “.