vsupalov

Generate a distinctive color palette

November 10, 2013 [ javascript | golang ]

Recently I needed a set number of distinctive colors (16) for a data visualization task. Here is some Go code, that uses the marvelously documented go-colorful library:

package main

import (
    "fmt"
    "os"
    "strings"
    "github.com/lucasb-eyer/go-colorful"
)

var labels = [...]string{
    "Laning Presence","Jungle","Defend","Push","Escape",
    "Gank","Farm","Stack","Pull","Teamfight","Roshan",
    "Ward","Counterward","Harass","Contest Pull","Fight"}

func main() {
    num_colors := len(labels)

    pal, err := colorful.HappyPalette(num_colors)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    colors := make([]string, num_colors)
    for i := 0; i < num_colors; i++ {
        colors[i] = fmt.Sprintf("\"%v\": \"%v\"", labels[i],pal[i].Hex())
    }

    fmt.Printf("colors = {\n")
    fmt.Printf("    %v\n",strings.Join(colors, ", "))
    fmt.Printf("}\n")
}

The output of this code is a JavaScript dictionary. The same approach can be used for any other language where you do not wish to deal with the hassle of generating colors during runtime.

Want to be notified when I publish new content?

Just enter your name and email below. You will also get content that I share exclusively with the list. Zero spam!