How to color charts of variable length data series

I’m using a Chart.js library in my package and I needed to color series of bars and pie slices which have variable data array lengths. I came up with the following algorithm which you can easily adapt. Hope it may be useful to someone using charts. I’m using HSL colors. Please feel free to improve it.

    $hsl_H = 0;
    $hsl_S = 90;
    $hsl_L = 80;

    foreach ($items as $item) {
        if ($hsl_H === 135) {
            $hsl_H += 45;
        }
        elseif ($hsl_H === 360) {
            $hsl_H = 0;
            $hsl_L += 1;
        }
    	
        if ($hsl_L === 91) {
            $hsl_H = 0;
            $hsl_S -= 30;
            $hsl_L = 80;
        }
        
        if ($hsl_S === 0) {
            $hsl_H = 0;
            $hsl_S = 90;
            $hsl_L = 80;
        }
        
        $colors[] = 'hsl(' . $hsl_H . ',' . $hsl_S . '%,' . $hsl_L . '%)';
        
        $hsl_H += 45;
    }
    
    $this->set('colors', json_encode($colors));

PS. It’s probably worth skipping $hsl_H === 135 because light green color is barely distinguishable from yellow and not clearly visible on a page

Nice! How does this compare with using a palette plugin like chartjs-plugin-colorschemes?

Current chartjs is is v3.5
colorschemes currently only works work with chartjs v2 and fails with v3+

For UCP charts I took the alternative approach of supporting a paste/import of schemes copied from pretty much any online colour scheme generator. Chart Design :: c5Magic

I expect colorschemes could be compatible soon.

1 Like

I had to sort of reinvent the wheel a little. I really wanted to use my own palette of various colors to start with, to start with a color I like and then after making a round to start changing the HSL. It works pretty nicely, the colors are brilliant. Although that may not suit every one’s needs.

1 Like

Nice, those examples look really nice. Reminds me of citrus fruit :slight_smile: