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