jpgraph基于其值的每个条形图的不同颜色

时间:2016-08-11 00:59:51

标签: php graph colors jpgraph

我是使用jpgraph的新手,我有一个条形图,我希望它根据其值为每个条形图提供不同的颜色,

所以在百分比的情况下,当条形值为< 80时,我希望它是红色条,当>= 80 && <85为bw 时黄条,当>= 85 绿条

我所能做的就是给出情节中所有条形的相似颜色

这里是代码,如果你可以帮我添加条件格式,请帮忙!

 $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();

1 个答案:

答案 0 :(得分:2)

您可以将每个条形图的颜色放在一个数组中,并检查每个数据值是否可以指定所需的颜色:

$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();