I’m deep into a Pluralsight course on PrimeNG, and have started to cover some of the niceties of PrimeNG charts.

The charting component is a wrapper around Chart.js, and one of the.. um.. interesting parts of the very cool Chart.js is that it has no default slice/bar colours.

Turns out this is a much requested feature and someone on that very thread went to the trouble of putting together a nice set of colours based around Google Charts.

But…

I don’t want to hand-assign the colours each time.

So..

The challenge: Write a function that will take an arbitrarily long pie chart dataset, and assign funky complimentary chart colours to each slice (so that the colour selection wraps around after depleting the set of funky colours).

Here’s my stab. First, setup a constant at the top of your TypeScript controller:

const DEFAULT_COLORS = ['#3366CC', '#DC3912', '#FF9900', '#109618', '#990099',
'#3B3EAC', '#0099C6', '#DD4477', '#66AA00', '#B82E2E',
'#316395', '#994499', '#22AA99', '#AAAA11', '#6633CC',
'#E67300', '#8B0707', '#329262', '#5574A6', '#3B3EAC']

Then inside the class, setup a routine to map the dataset into our set of default colours for each pie:

private configureDefaultColours(data: number[]): string[] {
    let customColours = []
    if (data.length) {

    customColours = data.map((element, idx) => {
        return DEFAULT_COLORS[idx % DEFAULT_COLORS.length];
    });
    }

    return customColours;
}

Then last of all, call that routine with your data whenever you need to generate some colours for your chart, and you’ll get back an array of colours to keep things fresh:

private hoursByProject = [
    {id: 1, name: 'Payroll App', hoursSpent: 8},
    {id: 2, name: 'Agile Times App', hoursSpent: 16},
    {id: 3, name: 'Point of Sale App', hoursSpent: 24},
]

private pieData = this.hoursByProject.map((proj) => proj.hoursSpent);
private pieLabels = this.hoursByProject.map((proj) => proj.name);
private pieColors = this.configureDefaultColours(this.pieData);

private hoursByProjectChartData = {
    labels: this.pieLabels,
    datasets: [
    {
        data: this.pieData,
        backgroundColor: this.pieColors,
    }
    ]
};

And you have yourself a chart with some funky default colours… Voila!

Bring the Colours On

If you love this sort of stuff, you’ll probably enjoy my upcoming Pluralsight course on PrimeNG! Stay tuned!