Skip to content

Instantly share code, notes, and snippets.

@romanbarczynski
Created June 28, 2013 22:23
Show Gist options
  • Save romanbarczynski/5888632 to your computer and use it in GitHub Desktop.
Save romanbarczynski/5888632 to your computer and use it in GitHub Desktop.
Generate finite number of colors (hex values ready for rrdtool, without leading '#') that are distinguishable on stack graphs. Usage: my @Colors = gen_colors(10);
sub gen_colors {
my $total = shift;
my @colors = ();
# round up to even number of colors:
$total = floor($total/2+1)*2;
# but divide by 1 more so first and last is different:
my $step = 360 / ($total+1);
for (my $i=0; $i<$total; $i+=1) {
my ($s, $v) = ($i%2) ? (90, 90) : (100, 60);
push @colors, rgb2hex(hsv2rgb($step*$i, $s, $v));
}
return @colors;
}
sub rgb2hex {
return sprintf("%2.2X%2.2X%2.2X", @_);
}
sub hsv2rgb {
my ($h, $s, $v) = @_;
my ($r, $g, $b);
my ($f, $i, $h_temp, $p, $q, $t);
$s /= 100 if ($s > 1);
$v /= 100 if ($v > 1);
if ($s == 0) {
$r = $g = $b = $v;
} else {
if ($h == 360) { $h_temp = 0; } else { $h_temp = $h; }
$h_temp /= 60;
$i = int($h_temp);
$f = $h_temp - $i;
$p = $v * (1 - $s);
$q = $v * (1 - ($s * $f));
$t = $v * (1 - ($s * (1 - $f)));
if ($i == 0) {$r = $v; $g = $t; $b = $p;}
if ($i == 1) {$r = $q; $g = $v; $b = $p;}
if ($i == 2) {$r = $p; $g = $v; $b = $t;}
if ($i == 3) {$r = $p; $g = $q; $b = $v;}
if ($i == 4) {$r = $t; $g = $p; $b = $v;}
if ($i > 4) {$r = $v; $g = $p; $b = $q;}
}
return (int($r*255), int($g*255), int($b*255));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment