Set Different Color For Each Bar in a Bar Chart in ChartJS

[Simple Trick]-Set Different Color For Each Bar in a Bar Chart in ChartJS

In this article, we’re going to focus on how we can give our background color a different way of coloring. Normally, you would be able to put in just an array with all these hardcoded values.

So first of all, this question came from one of my other posts about How to Create a Stacked Bar Chart Using Chart Js Example? which is an absolutely interesting topic. So a special thank you to our reader for asking the question.

So first of all, what we need to do is we need to create an HTML page and then add Chartjs CDN reference for getting started.

How to use set the color for each bar in a bar chart using chartjs?

In the Below example, we want the bars in this graph to have different colors that I choose myself i.e hard code fixed color. Because we don’t want to use random colors for each of the bars.

Set Different Color For Each Bar in a Bar Chart in ChartJS

So now we have a bar chart. And basically quite simple, the easiest way to do coloring on the bar chart is basically with backgroundColor option.

backgroundColor: ["#ffb3b3", "#800000", "#b3ffec", "#009973", "#d5ff80", "#558000", "#ffdf80", "#997300", "#adadeb", "#24248f", "#6666ff","#000066"]

Real Time Example

<!DOCTYPE html>
<html>
<head>
    <title>Set Different Color For Each Bar in a Bar Chart Using chart.js</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
</head>
<body>
    <div style="margin-left:5%;margin-right:5%">
        <canvas id="BarchatCanvas" style="width:80%"></canvas>
    </div>
    <script>
        var BarchartData = {
            labels: [
                "Jan",
                "Feb",
                "Mar",
                "Apr",
                "May",
                "June",
                "July",
                "Aug",
                "Sep",
                "Oct",
                "Nov",
                "Dec"
            ],
            datasets: [
                {
                    label: "Projected sales",
                    backgroundColor: ["#ffb3b3", "#800000", "#b3ffec", "#009973", "#d5ff80", "#558000", "#ffdf80", "#997300", "#adadeb", "#24248f", "#6666ff","#000066"],
                    borderWidth: 1,
                    data: [42, 56, 9, 52, 66, 87, 51, 42, 32, 88,150,125]
                }
            ]
        };
        const config = {
            type: 'bar',
            data: BarchartData,
            options: {
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            },
            title: {
                display: true,
                text: "Bar Chart with Diffrent Color"
            }
        };

        window.onload = function () {
            new Chart("BarchatCanvas", config);
        };

    </script>

</body>
</html>

Different color for each bar in a bar chart with Random Color

if you need a different color for each bar in a Bar Chart then you can use the below example. Here we have created a callback function for backgroundColor that returns the random color for each bar in the bar chart.

backgroundColor: color => {
                        var r = Math.floor(Math.random() * 255);
                        var g = Math.floor(Math.random() * 255);
                        var b = Math.floor(Math.random() * 255);
                        return "rgba(" + r + "," + g + "," + b + ", 0.5)";
                    }

random color for each barchart

<!DOCTYPE html>
<html>
<head>
    <title>Set Different Color For Each Bar based on value Using chart.js</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
</head>
<body>
    <div style="margin-left:5%;margin-right:5%">
        <canvas id="BarchatCanvas" style="width:80%"></canvas>
    </div>
    <script>
        var BarchartData = {
            labels: [
                "Jan",
                "Feb",
                "Mar",
                "Apr",
                "May",
                "June",
                "July",
                "Aug",
                "Sep",
                "Oct",
                "Nov",
                "Dec"
            ],
            datasets: [
                {
                    label: "Projected sales",
                    backgroundColor: color => {
                        var r = Math.floor(Math.random() * 255);
                        var g = Math.floor(Math.random() * 255);
                        var b = Math.floor(Math.random() * 255);
                        return "rgba(" + r + "," + g + "," + b + ", 0.5)";
                    },
                    borderWidth: 1,
                    data: [42, 56, 9, 52, 66, 87, 51, 42, 32, 88,150,125]
                }
            ]
        };
        const config = {
            type: 'bar',
            data: BarchartData,
            options: {
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            },
            title: {
                display: true,
                text: "Bar Chart with Diffrent Color"
            }
        };

        window.onload = function () {
            new Chart("BarchatCanvas", config);
        };

    </script>

</body>
</html>

Code explanation

So what I’m going to do is a very simple trick, but it will only work for everything except for the line chart. So what I’m going to do here, I’m going to just delete the hardcoded backgroundColor array and here in the backgroundColor I’m going to create a callback function because remember in chart js you’re allowed to put in functions if they are indicated as scriptable. So border color and background color are scriptable items.

so what we’re going to do here is it’s going to put in a script, We’re going to make it a function because basically a callback function which will be based on the conditions and this will be set color.

What I want maybe first is to make sure you see this here. So let’s do a console walk for that. So you can see what we are able to see here. Save that refresh, open the developer tab and let’s see what’s going on.

You can see here the data index and value that’s based on what you want to know or the index number. So if you want to highlight only the last three values or the first three values, you could do it based on condition.

Index based color

How do I change the color of bar chart based on value?

In this example, we’re going to answer one the reader’s question, which is how to change the color of the bars in a bar chart based on the value i.e How do I change the color of my bar chart based on value? So let’s start and explore how to do.
we’re going to put a color based on the condition i.e if value is greater then equal to 50 then red else  it will be green.

How do I change the color of my bar chart based on value

<!DOCTYPE html>
<html>
<head>
    <title>Set Different Color For Each Bar based on value Using chart.js</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
</head>
<body>
    <div style="margin-left:5%;margin-right:5%">
        <canvas id="BarchatCanvas" style="width:80%"></canvas>
    </div>
    <script>
        var BarchartData = {
            labels: [
                "Jan",
                "Feb",
                "Mar",
                "Apr",
                "May",
                "June",
                "July",
                "Aug",
                "Sep",
                "Oct",
                "Nov",
                "Dec"
            ],
            datasets: [
                {
                    label: "Projected sales",
                    backgroundColor: color => {
                        if (color.raw >= 50) {
                            return "green";
                        }
                        else {
                            return "red";
                        }
                    },
                    borderWidth: 1,
                    data: [42, 56, 9, 52, 66, 87, 51, 42, 32, 88,150,125]
                }
            ]
        };
        const config = {
            type: 'bar',
            data: BarchartData,
            options: {
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            },
            title: {
                display: true,
                text: "Bar Chart with Diffrent Color"
            }
        };

        window.onload = function () {
            new Chart("BarchatCanvas", config);
        };

    </script>

</body>
</html>

Ashok Patel

I'm a software engineer, having good experience in software programming web designing with great command on ASP.NET, React JS, Angular JS,.NET Core HTML5, JavaScript, T-SQL, JQuery.
Also have great experience in Electronics and electrical engineers design.
I like to do RND and Research.

Your Header Sidebar area is currently empty. Hurry up and add some widgets.