How to create dynamic color list for charts
Basically i have a different value in my database or each values contain each percentage and i need to show this percentages in pie chart with different colors ....
This is the example code of pie chart in static way
<color value="#99CDFB"/>
<color value="#3366FB"/>
<color value="#0000FA"/>
<color value="#F8CC00"/>
<color value="#F89900"/>
<color value="#F76600"/>
but i need dynamic way using PHP ( for loop / foreach loop) like this
$color = "";
foreach($data as $data){
echo '<color value=".$color."/>';
}
and i don't know to create dynamic color list also see the screenshot for verification
For random string of colors, here:
function randColor( $numColors ) {
$chars = "ABCDEF0123456789";
$size = strlen( $chars );
$str = array();
for( $i = 0; $i < $numColors; $i++ ) {
for( $j = 0; $j < 6; $j++ ) {
$str[$i] .= $chars[ rand( 0, $size - 1 ) ];
}
}
return $str;
}
Then, in your function, use $colors = randColor( 6 );
to create a total of 6 different colors. After that, here's your output color method.
foreach( $colors as $codeColor ) {
echo "<color value=\"#{$codeColor}\" />\n";
}
I would prefer to use an aproach using dechex() function. First you have to prepare three 0-255 random numbers, convert them to hex and join to make a string. Then you can also use the calculated numbers to assign text color: black for light colors or white for darker, like:
if( ($r + $g + $b) / 3 > 126)
$textcolor="#000000";
else
$textcolor="#FFFFFF";
Another idea is to generate shaded random colors. You may first generate three random numbers from 0 to let say 40 - for the first color, then, second color will be from 40 to 80, and so on...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With