[Chartjs]-How to change color of column in chart js

1๐Ÿ‘

โœ…

I hope Iโ€™ve solve tour problem:

function updateChart(chart){
    let val = 2;
    let updatedValues = [];
    chart.data.datasets[0].data.forEach((e,i)=>{
    if(e===0){
      updatedValues.push('green');
      chart.data.datasets[0].data[i] = val;
      chart.data.datasets.push({data:
        Array.from({length:chart.data.datasets[0].data.length},function(el,j){
            if(i===j) return -val
        })})
    } else {
        updatedValues.push(chart.data.datasets[0].backgroundColor)
    }

  })
  chart.data.datasets.forEach(e=>{
    e.backgroundColor = updatedValues;
  })

  chart.update()
}

And fiddle to testing: https://jsfiddle.net/7Lbjmw6r/

1๐Ÿ‘

Hi you have to give a array in the backgroundColor-Parameter with in the dataset: see here:

var labels = ["001", "002", "003", "004", "005", "006", "007"];
var data = [20, 59, 80, 81, 56, 55, 40];
for (var i = 0, len = labels.length; i < len; i++) {
   **background_colors**.push(getRandomColor());
}

var barChartData = {
  labels: labels,
  datasets: [{
    label: "My First dataset",
    fillColor: "rgba(220,220,220,0.5)", 
    strokeColor: "rgba(220,220,220,0.8)", 
    highlightFill: "rgba(220,220,220,0.75)",
    highlightStroke: "rgba(220,220,220,1)",
    backgroundColor: **background_colors**,
    data: data
  }]
};

This should work!

Leave a comment