vsupalov

Generate a distinctive color palette

November 10, 2013

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.

Join the Mailing List

Subscribe to get weekly updates and my latest articles by email.

    (About the content, privacy, analytics and revocation).

    We won't send you spam. Unsubscribe at any time.

    Powered By ConvertKit