How to create dynamic color list for charts

爱⌒轻易说出口 提交于 2019-12-22 09:07:32

问题


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


回答1:


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";
}



回答2:


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...



来源:https://stackoverflow.com/questions/9761234/how-to-create-dynamic-color-list-for-charts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!