phpgraphcolorsjpgraph

jpgraph different color for each bar based on its value


I'm new to using jpgraph and i have a bar plot that i want it to have different color for each bar based in its value,

so in case of a percentage, when the bar value is < 80 i want it to be a red bar, when it is >= 80 && <85 to bw a Yellow bar and when it is >= 85 a green bar

all i was possible to do is give a similar color to all the bars in the plot

here is the code if you can help me add the conditional formatting to it please help !

 $datay=array(90,82,70,30,100,85);

// Create the graph. These two calls are always required
$graph = new Graph(300,200,"auto");    
$graph->SetScale("textlin");

// Add a drop shadow
$graph->SetShadow();

// Adjust the margin a bit to make more room for titles
$graph->img->SetMargin(40,30,20,40);

// Create a bar pot
$bplot = new BarPlot($datay);

// Adjust fill color

$graph->Add($bplot);
$bplot->value->Show();

/* I tried to add if statement here but the pic won't render */
$bplot->SetFillColor('orange');

// Display the graph
$graph->Stroke();

Solution

  • You can put the color for each bar in an array and by check every data value it's possible to assign the desired color:

    $datay=array(90,82,70,30,100,85);
    $barcolors = array();
    
    // Create the graph. These two calls are always required
    $graph = new Graph(300,200,"auto");    
    $graph->SetScale("textlin");
    
    // Add a drop shadow
    $graph->SetShadow();
    
    // Adjust the margin a bit to make more room for titles
    $graph->img->SetMargin(40,30,20,40);
    
    // Create a bar pot
    $bplot = new BarPlot($datay);
    
    // Adjust fill color
    
    $graph->Add($bplot);
    $bplot->value->Show();
    
    foreach ($datay as $datayvalue) {
        if ($datayvalue < '80') $barcolors[]='red';
        elseif ($datayvalue >= '80' && $datayvalue < '85') $barcolors[]='yellow';
        elseif ($datayvalue >= '85') $barcolors[]='green';
    }
    
    $bplot->SetFillColor($barcolors);
    
    // Display the graph
    $graph->Stroke();