DEV Community

Cover image for How to add dynamic colors in Chartjs
Taimoor khan
Taimoor khan

Posted on • Updated on

How to add dynamic colors in Chartjs

If you are stuck in hardcoding color values for each dataset and whenever there is new entry in a dataset your code broke, if yes this article is for you...

Recently I was working with chartjs in React. Every time a new data was populated I had to add new color values for that label and data manually, after spending about 1.5 hours on the internet, I finally found a solution to dynamically add colors in chartJS.

Setting up project

You can use this replit for your reference, just start the project and start playing.

Explanation

Following this amazing article, using D3's Chromatic color scale, we will be creating dynamic color ranges for our charts, D3's Scale Chromatic library provides many color scales, we have used their interpolate color scales. All of the interpolate color scales have a domain of [0, 1]. If you want to get deeper check out this amazing article. To simplify, I have created a function chartData()

chartData() returns data object which we can then pass to any Chart component. This function accepts a data object which contains labels, colorRangeInfo, scale and dataLabel

chartData({
    labels: ["China", "UAE", "Yemen", "Pakistan", "Saudia"],
    colorRangeInfo: {
    colorStart: 0,
    colorEnd: 1,
    useEndAsStart: false,
    },
    scale: d3.interpolateBlues,
    dataLabel: "data for doughnut chart",
})
Enter fullscreen mode Exit fullscreen mode

Labels : accepts list of data labels which will be displayed as labels.

colorRangeInfo() : accepts object containing d3 chromatic color range (0,1) useEndAsStart : true will reverse the color range.

const colorRangeInfo = {
    colorStart: 0,
    colorEnd: 1,
    useEndAsStart: false,
};
Enter fullscreen mode Exit fullscreen mode

The scale property accepts d3.interpolate which gives you various combinations such:
interpolateIferno

interpolateCool

You can play around with different variation by using different interpolate color scales.

Please share your thoughts if this article was useful for you. I would love hear back from you guys if you have any better solution for this.

Top comments (0)