Change pie colors Chart php

Asked

Viewed 368 times

2

Good afternoon!
I’m creating a circular graph, the data I search from the database.
However I do not know how to change the colors of the circular graphic sectors, to make it clearer I will show here what I intend.
The code is as follows::

include "../classif/BD/ligabd.php"; ... `

  google.charts.load("current", {packages:["corechart"]});;
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() 
  {
   var data = google.visualization.arrayToDataTable([
    ['classificacao','Number'],
    <?php
    while ($row=mysqli_fetch_array($result)) 
    {
      echo "['".$row["classificacao"]."', ".$row["number"]."],";
    }
    ?>
    ]);
   var options = {
    title:'Classificações do refeitório', 
    is3D:true
  };
  var chart = new google.visualization.PieChart(document.getElementById('piechart'));
  chart.draw(data,options);
}


Chart of the cafeteria classifications `
The output is as follows::
inserir a descrição da imagem aqui


What I intended was instead of "yellow" being the color blue, the color was yellow, where it says green, instead of being red that was green, so on...

1 answer

3


You have a field colors in options.

Example

var options = {
  // .. outras opcoes
  colors: ['#e0440e', '#e6693e', '#ec8f6e', '#f3b49f', '#f6c7b6']
};

chart.draw(data, options);

If you do not control the data order but want a specific item to have a certain color, you can change your while a little bit.

<?php
$colors = [];
while ($row=mysqli_fetch_array($result)) 
{
  switch ($row['classificacao']) {
    case 'amarelo' : $colors[] = 'yellow'; break; // 'amarelo' deve ser o item que queres que seja amarelo. 'yellow' deve por o código da cor que queres
    case 'vermelho': $colors[] = 'red';    break;
    case 'azul'    : $colors[] = 'blue';   break;
  }
  echo "['".$row["classificacao"]."', ".$row["number"]."],";
}
?>
var options = {
  title:'Classificações do refeitório', 
  is3D:true,
  colors: <?php echo json_encode($colors) ?>
};
  • But how do I say that I want red to be red, yellow to be yellow, etc... ?

  • It’s the same order as in data

  • Heheh, thank you!

  • I put an example of how you can control colors if you can’t control the order of what’s in data

  • Perfect! Very good!

  • By the way, to change the name of the "subtitles" would need to change thequery and change in var data...?

  • Yes. Since I don’t see the code where you add those pins, I assume that’s the value you have in $row["classificacao"], the first array item you pass to arrayToDataTable is the label, the second is the value of that label

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.