How to add dynamic colors in Chartjs
Taimoor khan
Posted on December 23, 2020
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",
})
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,
};
The scale property accepts d3.interpolate
which gives you various combinations such:
interpolateIferno
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.
Posted on December 23, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.