user

Shilpa

27 Feb 2022

Angular - PrimeNG charts adding colors for each legends dynamically

Angular

I am using the PrimeNg library to show statistics for my client's application data.

Let's say, I have 3 entities (legends) to show on the pie chart. I can give fix color codes in hex like ('#3366CC', '#DC3912', '#FF9900'), so it will render 3 colors for different percentages of the pie portion.

I am trying to show number of records with different colors, with respective percentage of portion dynamically, so let's say - I have 4 or 8 or 15 number of legends to show, How do I manage colors?

Issue: It takes same color that I gave in the color format. For more legends, it should show different colors?

How do I fix this issue to show a pie chart with multiple colors?

Comments

Rakshit

28 Feb 2022

Best Answer

best answer

PrimeNg library uses Chart.js internally. So you can add following code to your component. Let's say, your max number of legends will be 15, so add 15 to 20 colors to the below array.

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

If you don't know about color coding and hash codes of different colors, I recommend you to go through ColorPalette; It will give you the best color combinations.

Now, set up a routine to map the dataset into our set of default colors for each pie charts.

private configureDefaultColors(data: number[]): string[] {
let customColours = []
 if (data.length) {
 customColours = data.map((element, idx) => {
 return DEFAULT_COLORS[idx % DEFAULT_COLORS.length];
 });
 }
return customColours;
}

After that, call your routine,

private demoProject = [
{id: 1, name: 'Payroll App', hoursSpent: 8},
{id: 2, name: 'Agile Times App', hoursSpent: 20},
{id: 3, name: 'Point of Sale App', hoursSpent: 45},
]
 
 private pieData = this.demoProject.map((proj) => proj.hoursSpent);
 private pieLabels = this.demoProject.map((proj) => proj.name);
 private pieColors = this.configureDefaultColors(this.pieData);
private demoProjectChartData = {
labels: this.pieLabels,
datasets: [
	{
	data: this.pieData,
	backgroundColor: this.pieColors,
	}
]};

Bingo, you did it, now you will have multiple funky colors ready for your Pie Charts, Same logic is also applicable for Bar, Line or bubble charts.

References: For more information, you can visit Beingcoders,  Chart.js , and ColorPalette.

© 2024 Copyrights reserved for web-brackets.com