Search code examples
chart.jspie-chart

Configure Pie Chart Colors Using Chart.js and PHP


I have been trying to enable different colors for different areas but I cannot find a way of having different colors for different objects.

Am fetching data from database and then working on it and working on it as follows.

I would appreciate your views on how to change colors for different items

//looping through the data
for(var i in data) {
    CarPrices.push(data[i].name);
    score.push(data[i].price);
}

//Working with data fetched from database
var chartdata = {
    labels: player,
    datasets : [
        {
             //Trying to change background color for each element                               
             label: 'Car Prices',
             backgroundColor: [
                  "#FF6384",
                  "#36A2EB",
                  "#FFCE56"
             ],
             //Trying to change background color for each element**
             hoverBackgroundColor: [
                  "#FF6384",
                  "#36A2EB",
                  "#FFCE56"
             ],

        }
    ]
};

Solution

  • It is possible to control the color of each slice in a pie/doughnut chart using the backgroundColor dataset property.

    It looks like you were attempting to do this in your question, but here is a full working example so that you can leverage it for your needs.

    var config = {
      type: 'doughnut',
      data: {
        datasets: [{
          data: [300, 50, 100, 40, 10],
          backgroundColor: [
            window.chartColors.red,
            window.chartColors.orange,
            window.chartColors.yellow,
            window.chartColors.green,
            window.chartColors.blue,
          ],
        }],
        labels: [
          "Red",
          "Orange",
          "Yellow",
          "Green",
          "Blue"
        ]
      },
      options: {
        responsive: true,
        legend: {
          display: true,
          labels: {
            padding: 20
          },
        },
        tooltips: {
          enabled: false,
        }
      }
    };
    

    Here is a working Codepen example.