Is there a way to dynamically change the colors of bars in a chart created using chart.js 2.6 based on whether the values are above or below zero? The data for the graph series is currently generated randomly but will eventually come from a database query.
function adjustBarColors(chart) {
var datasets = chart.data.datasets;
var labelLen = chart.data.labels.length;
if (datasets[0]) {
for (i = 0, len = datasets.length; i < len; i++) {
try {
for (j = 0, len = labelLen; j < len; j++) {
datasets[i].data[j] = getRandomInt(-100, 100);
}
} catch (e) {
console.log(e.message);
}
}
}
}
The current appearance of the chart can be viewed here:
https://i.sstatic.net/CzjUh.png
I aim to have bars above zero displayed in blue and bars below zero in red.
Your assistance and feedback are greatly appreciated. Thank you in advance!
Griff
** Edit ** Included additional code provided by another user:
var myBarChart = new Chart(wowChart, {
type: 'bar',
data: wowData,
plugins: [{
beforeDraw: function (c) {
var data = c.data.datasets[0].data;
for (var i in data) {
try {
var bar = c.data.datasets[0]._meta[0].data[i]._model;
if (data[i] > 0) {
bar.backgroundColor = '#07C';
} else bar.backgroundColor = '#E82020';
} catch (ex) {
console.log(ex.message);
}
console.log(data[i]);
}
}
}],
options: wowOptions
});
I am encountering exceptions in the console output every other line, along with the data elements.