As we all know that PrimeNg gave much effort to make Angular projects so easy, not only the Angular, but they also made more support to React and Vuejs libraries by providing the open-source and Most Powerful Angular UI Component Library.
While development you may find that your chart needs some improvement with some animations and color things, right? — So you are in the right place.
If you go through with the PrimeNg chart widget documentation, you can see they are using Chart.js internally, and one of the.. um.. interesting parts of the very cool Chart.js is that it has no default slice/bar colors.
The color combinations are totally user-defined.
You are free to apply colors statically or manually according to your choice, but let’s say what if you have a number of columns that are 7–8 or 10 numbers, then you will have ambiguity with assigning colors and legends manually. To cope up with the issue I made something which can be useful to you.
I don’t want to hand-assign the colors each time, so use the below code for the perfect solution. (so that the color selection wraps around after depleting the set of funky colors If you are developing your application for Industry, Honestly, I do not recommend using fancy colors for your theme design).
First, set up a constant at the top of your TypeScript class:
const DEFAULT_COLORS = ['#3366CC', '#DC3912', '#FF9900', '#109618', '#990099',
'#3B3EAC', '#0099C6', '#DD4477', '#66AA00', '#B82E2E',
'#316395', '#994499', '#22AA99', '#AAAA11', '#6633CC',
'#E67300', '#8B0707', '#329262', '#5574A6', '#3B3EAC']
If you don’t have much knowledge about color combinations, try this color palette to select the best colors and their Hash Codes.
Then inside the class, set up a routine to map the dataset into our set of default colors 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; }
At last, call that routine with your data whenever you need to generate some colors for your chart randomly for your selected entities, and you’ll get back an array of colors to keep things fresh:
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.configureDefaultColours(this.pieData);
private demoProjectChartData = {
labels: this.pieLabels,
datasets: [
{
data: this.pieData,
backgroundColor: this.pieColors,
}
]
};
And you have yourself a chart with some funky default colors… Bingo!!!
References:
Discover more from 9Mood
Subscribe to get the latest posts sent to your email.
0 Comments