Search code examples
javascriptchart.jsbackground-color

Chart.js - PieChart defined background color for specific dataset element


Community,

I am trying to have a Chart.js - PieChart with a defined background for each specific dataset element.

eg: The Dataset has a maximum of 3 elements: good, normal and bad. But it can also just have two or even one.

pieChartData () {
    let dataset = []
    let labels = []
    let bgColor = [
        'green',
        'yellow',
        'red'
    ]
    for (var key in this.accountProfile.categories) {
        if (this.accountProfile.categories.hasOwnProperty(key)) {
            labels.push(key)
            dataset.push(this.accountProfile.categories[key].volume)
        }
    }
    return { 
        labels: labels,
        datasets: [
            { 
                data: dataset,
                backgroundColor: bgColor
            }
        ]
    }
}

I would like to have: good as green, normal as yellow, bad as red

but if my dataset has just normal and bad, the colors get mixed up and normal is green instead of yellow, bad is yellow instead of red and so on.

Any help would be much appreciated. Thanks, J


Solution

  • You can define array where colors are values and good, bad and normal are keys, see next:

    let chartColors = [];
    chartColors['good'] = 'green';
    chartColors['bad'] = 'red';
    chartColors['normal'] = 'yellow';
    

    Then the next step would be to add new array variable where you will push on the same way as you have done for labels:

    someColorVar.push(chartColors[key]); 
    

    Then replace bgcolor with someColorVar.