Firstly, let a variable remember an instance of your chart.
let yourChart = new Chart(ctxBar, {
type: 'bar',
data: {
labels: labels,
datasets: datasets
},
});
Secondly, the thing I mostly struggled with was getting the data structure in the right format before updating the chart. So after looking at the data
key structure of chart js object:
data: {
labels: ['Jan', 'Feb'],
datasets: [{
label: 'Net sales',
data: data
}, {
label: 'Cost of goods sold',
data: data
}, {
label: 'Gross margin',
data: data
}]
}
Notice the data
key value is an object consisting of two keys, labels
and datasets
. labels
key' value is an array, while datasets
key' value is also an array with an object as value.
Therefore, to remove
labels and datasets from a chart instance I used:
yourChart.data.labels = [];
yourChart.data.datasets = [{}];
yourChart.update();
To add
labels and datasets to a chart instance I used:
yourChart.data.labels = ['label 1', 'label 2'];
yourChart.data.datasets = [{
label: 'column lables',
data: [450, 50],
backgroundColor: ["#dc3545", "#ffb759"]
}];
yourChart.update();
Prepare server side
The labels and datasets values can be prepared server side as follows (in my case php):
$datajs = function ($data, $bg_colour) // function emulating chart js datasets key value structure
{
return [
'data' => $data,
'backgroundColor' => $bg_colour
];
};
$datasets = [];
$labels = ['label 1', 'label 2'];
$datasets[] = $datajs([42,10], ["#dc3545", "#ffb759"]);
$datasets[] = $datajs([100,5], ["#dc3545", "#ffb759"]);
To just replace data from data key value from datasets (I did not test this)
yourChart.data.datasets.forEach((dataset) => {
dataset.data = [];
});
yourChart.update();
// if you have an array of arrays
let array = [[42,20],[58,68],[78,1]];
let length = yourChart.data.datasets.length;
for (let i = 0; i < array.length; i++) {
const element = array[i];
if (i < length) {
yourChart.data.datasets[i].data = element;
} else {
yourChart.data.datasets[] = {data: element};
}
}
yourChart.update();