score:63

Accepted answer

after looking into the chart.bar.js file i've managed to find the solution. i've used this function to generate a random color:

function getrandomcolor() {
    var letters = '0123456789abcdef'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[math.floor(math.random() * 16)];
    }
    return color;
}

i've added it to the end of the file and i called this function right inside the "fillcolor:" under

helpers.each(dataset.data,function(datapoint,index){
                    //add a new point for each piece of data, passing any required data to draw.

so now it looks like this:

helpers.each(dataset.data,function(datapoint,index){
                    //add a new point for each piece of data, passing any required data to draw.

                    datasetobject.bars.push(new this.barclass({
                        value : datapoint,
                        label : data.labels[index],
                        datasetlabel: dataset.label,
                        strokecolor : dataset.strokecolor,
                        fillcolor : getrandomcolor(),
                        highlightfill : dataset.highlightfill || dataset.fillcolor,
                        highlightstroke : dataset.highlightstroke || dataset.strokecolor
                    }));
                },this);

and it works i get different color for each bar.

score:0

i have just got this issue recently, and here is my solution

var labels = ["001", "002", "003", "004", "005", "006", "007"];
var data = [20, 59, 80, 81, 56, 55, 40];
for (var i = 0, len = labels.length; i < len; i++) {
   background_colors.push(getrandomcolor());// i use @benjamin method here
}

var barchartdata = {
  labels: labels,
  datasets: [{
    label: "my first dataset",
    fillcolor: "rgba(220,220,220,0.5)", 
    strokecolor: "rgba(220,220,220,0.8)", 
    highlightfill: "rgba(220,220,220,0.75)",
    highlightstroke: "rgba(220,220,220,1)",
    backgroundcolor: background_colors,
    data: data
  }]
};

score:0

code based on the following pull request:

datapoint.color = 'hsl(' + (360 * index / data.length) + ', 100%, 50%)';

score:0

what i've done is create a random color generator as many here have suggested

function dynamiccolors() {
        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)";
    }

and then coded this

var chartcontext = document.getelementbyid('line-chart');
    let linechart = new chart(chartcontext, {
        type: 'bar',
        data : {
            labels: <?php echo json_encode($names); ?>,
            datasets: [{
                data : <?php echo json_encode($salaries); ?>,
                borderwidth: 1,
                backgroundcolor: dynamiccolors,
            }]
        }
        ,
        options: {
            scales: {
                yaxes: [{
                    ticks: {
                        beginatzero: true
                    }
                }]
            },
            responsive: true,
            maintainaspectratio: false,
        }
    });

notice there is no parantheses at the function call this enables the code to call the function every time, instead of making an array this also prevents the code from using the same color for all the bars

score:0

pass a color parameter in datapoints like below for each bar:

{y: your value, label: your value, color: your color code}

enter image description here

score:0

enter image description here

function getrandomcolor() {

        const colors = [];
        var obj = @json($year);
        const length = object.keys(obj).length;
        for(let j=0; j<length; j++ )
        {
            const letters = '0123456789abcdef'.split('');
            let color = '#';
            for (let i = 0; i < 6; i++ ) {
                color += letters[math.floor(math.random() * 16)];
            }
            colors.push(color);
        }
        return colors;
    }

use this function for different colors

score:1

try this :

  function getchartjs() {
        **var dynamiccolors = function () {
            var r = math.floor(math.random() * 255);
            var g = math.floor(math.random() * 255);
            var b = math.floor(math.random() * 255);
            return "rgb(" + r + "," + g + "," + b + ")";
        }**

        $.ajax({
            type: "post",
            url: "admin_default.aspx/getchartbyjeniskerusakan",
            data: "{}",
            contenttype: "application/json; charset=utf-8",
            datatype: "json",
            success: function (r) {
                var labels = r.d[0];
                var series1 = r.d[1];
                var data = {
                    labels: r.d[0],
                    datasets: [
                        {
                            label: "my first dataset",
                            data: series1,
                            strokecolor: "#77a8a8",
                            pointcolor: "#eca1a6"
                        }
                    ]
                };

                var ctx = $("#bar_chart").get(0).getcontext('2d');
                ctx.canvas.height = 300;
                ctx.canvas.width = 500;
                var linechart = new chart(ctx).bar(data, {
                    beziercurve: false,
                    title:
                      {
                          display: true,
                          text: "productwise sales count"
                      },
                    responsive: true,
                    maintainaspectratio: true
                });

                $.each(r.d, function (key, value) {
                    **linechart.datasets[0].bars[key].fillcolor = dynamiccolors();
                    linechart.datasets[0].bars[key].fillcolor = dynamiccolors();**
                    linechart.update();
                });
            },
            failure: function (r) {
                alert(r.d);
            },
            error: function (r) {
                alert(r.d);
            }
        });
    }

score:1

this works for me in the current version 2.7.1:

function colorizepercentagechart(myobjbar) {

var bars = myobjbar.data.datasets[0].data;
console.log(myobjbar.data.datasets[0]);
for (i = 0; i < bars.length; i++) {

    var color = "green";

    if(parsefloat(bars[i])  < 95){
        color = "yellow";
    }
    if(parsefloat(bars[i])  < 50){
         color = "red";
    }

    console.log(color);
    myobjbar.data.datasets[0].backgroundcolor[i] = color;

}
myobjbar.update(); 

}

score:1

taking the other answer, here is a quick fix if you want to get a list with random colors for each bar:

function getrandomcolor(n) {
    var letters = '0123456789abcdef'.split('');
    var color = '#';
    var colors = [];
    for(var j = 0; j < n; j++){
        for (var i = 0; i < 6; i++ ) {
            color += letters[math.floor(math.random() * 16)];
        }
        colors.push(color);
        color = '#';
    }
    return colors;
}

now you could use this function in the backgroundcolor field in data:

data: {
        labels: count[0],
        datasets: [{
            label: 'registros en bds',
            data: count[1],
            backgroundcolor: getrandomcolor(count[1].length)
        }]
}

score:1

if you know which colors you want, you can specify color properties in an array, like so:

    backgroundcolor: [
    'rgba(75, 192, 192, 1)',
    ...
    ],
    bordercolor: [
    'rgba(75, 192, 192, 1)',
    ...
    ],

score:2

if you're not able to use newchart.js you just need to change the way to set the color using array instead. find the helper iteration inside chart.js:

replace this line:

fillcolor : dataset.fillcolor,

for this one:

fillcolor : dataset.fillcolor[index],

the resulting code:

//iterate through each of the datasets, and build this into a property of the chart
  helpers.each(data.datasets,function(dataset,datasetindex){

    var datasetobject = {
      label : dataset.label || null,
      fillcolor : dataset.fillcolor,
      strokecolor : dataset.strokecolor,
      bars : []
    };

    this.datasets.push(datasetobject);

    helpers.each(dataset.data,function(datapoint,index){
      //add a new point for each piece of data, passing any required data to draw.
      datasetobject.bars.push(new this.barclass({
        value : datapoint,
        label : data.labels[index],
        datasetlabel: dataset.label,
        strokecolor : dataset.strokecolor,
        //replace this -> fillcolor : dataset.fillcolor,
        // whith the following:
        fillcolor : dataset.fillcolor[index],
        highlightfill : dataset.highlightfill || dataset.fillcolor,
        highlightstroke : dataset.highlightstroke || dataset.strokecolor
      }));
    },this);

  },this);

and in your js:

datasets: [
                {
                  label: "my first dataset",
                  fillcolor: ["rgba(205,64,64,0.5)", "rgba(220,220,220,0.5)", "rgba(24,178,235,0.5)", "rgba(220,220,220,0.5)"],
                  strokecolor: "rgba(220,220,220,0.8)",
                  highlightfill: "rgba(220,220,220,0.75)",
                  highlightstroke: "rgba(220,220,220,1)",
                  data: [2000, 1500, 1750, 50]
                }
              ]

score:3

here is how i dealed: i pushed an array "colors", with same number of entries than number of datas. for this i added a function "getrandomcolor" at the end of the script. hope it helps...

for (var i in arr) {
    customers.push(arr[i].customer);
    nb_cases.push(arr[i].nb_cases);
    colors.push(getrandomcolor());
}

window.onload = function() {
    var config = {
        type: 'pie',
        data: {
            labels: customers,
            datasets: [{
                label: "nomber of cases by customers",
                data: nb_cases,
                fill: true,
                backgroundcolor: colors 
            }]
        },
        options: {
            responsive: true,
            title: {
                display: true,
                text: "cases by customers"
            },
        }
    };

    var ctx = document.getelementbyid("canvas").getcontext("2d");
    window.myline = new chart(ctx, config);
};

function getrandomcolor() {
    var letters = '0123456789abcdef'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[math.floor(math.random() * 16)];
    }
    return color;
}

score:7

here's a way to generate consistent random colors using color-hash

const colorhash = new colorhash()

const datasets = [{
  label: 'balance',
  data: _.values(balances),
  backgroundcolor: _.keys(balances).map(name => colorhash.hex(name))
}]

enter image description here

score:11

generate random colors;

function getrandomcolor() {
    var letters = '0123456789abcdef'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[math.floor(math.random() * 16)];
    }
    return color;
}

and call it for each record;

function getrandomcoloreachemployee(count) {
    var data =[];
    for (var i = 0; i < count; i++) {
        data.push(getrandomcolor());
    }
    return data;
}

finally set colors;

var data = {
    labels: jsondata.employees, // your labels
    datasets: [{
        data: jsondata.approvedratios, // your data
        backgroundcolor: getrandomcoloreachemployee(jsondata.employees.length)
    }]
};

score:17

as of august 2019, chart.js now has this functionality built in.

successful bar chart with different colored bars

you simply need to provide an array to backgroundcolor.

example taken from https://www.chartjs.org/docs/latest/getting-started/

before:

  data: {
        labels: ['january', 'february', 'march', 'april', 'may', 'june', 'july'],
        datasets: [{
            label: 'my first dataset',
            backgroundcolor: 'rgb(255, 99, 132)',
            bordercolor: 'rgb(255, 99, 132)',
            data: [0, 10, 5, 2, 20, 30, 45]
        }]
    },

after:

  data: {
        labels: ['january', 'february', 'march', 'april', 'may', 'june', 'july'],
        datasets: [{
            label: 'my first dataset',
            backgroundcolor: ['rgb(255, 99, 132)','rgb(0, 255, 0)','rgb(255, 99, 132)','rgb(128, 255, 0)','rgb(0, 255, 255)','rgb(255, 255, 0)','rgb(255, 255, 128)'],
            bordercolor: 'rgb(255, 99, 132)',
            data: [0, 10, 5, 2, 20, 30, 45]
        }]
    },

i just tested this method and it works. each bar has a different color.

score:18

here, i solved this issue by making two functions.

1. dynamiccolors() to generate random color

function dynamiccolors() {
    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)";
}

2. poolcolors() to create array of colors

function poolcolors(a) {
    var pool = [];
    for(i = 0; i < a; i++) {
        pool.push(dynamiccolors());
    }
    return pool;
}

then, just pass it

datasets: [{
    data: arrdata,
    backgroundcolor: poolcolors(arrdata.length),
    bordercolor: poolcolors(arrdata.length),
    borderwidth: 1
}]

score:22

you can call this function which generates random colors for each bars

var randomcolorgenerator = function () { 
    return '#' + (math.random().tostring(16) + '0000000').slice(2, 8); 
};

var barchartdata = {
        labels: ["001", "002", "003", "004", "005", "006", "007"],
        datasets: [
            {
                label: "my first dataset",
                fillcolor: randomcolorgenerator(), 
                strokecolor: randomcolorgenerator(), 
                highlightfill: randomcolorgenerator(),
                highlightstroke: randomcolorgenerator(),
                data: [20, 59, 80, 81, 56, 55, 40]
            }
        ]
    };

score:26

if you take a look at the library "chartnew" which builds upon chart.js you can do this by passing the values in as an array like so:

var data = {
    labels: ["batman", "iron man", "captain america", "robin"],
    datasets: [
        {
            label: "my first dataset",
            fillcolor: ["rgba(220,220,220,0.5)", "navy", "red", "orange"],
            strokecolor: "rgba(220,220,220,0.8)",
            highlightfill: "rgba(220,220,220,0.75)",
            highlightstroke: "rgba(220,220,220,1)",
            data: [2000, 1500, 1750, 50]
        }
    ]
};

score:68

solution: call the update method to set new values ​​:

var barchartdata = {
    labels: ["january", "february", "march"],
    datasets: [
        {
            label: "my first dataset",
            fillcolor: "rgba(220,220,220,0.5)", 
            strokecolor: "rgba(220,220,220,0.8)", 
            highlightfill: "rgba(220,220,220,0.75)",
            highlightstroke: "rgba(220,220,220,1)",
            data: [20, 59, 80]
        }
    ]
};

window.onload = function(){
    var ctx = document.getelementbyid("mycanvas").getcontext("2d");
    window.myobjbar = new chart(ctx).bar(barchartdata, {
          responsive : true
    });

    //nuevos colores
    myobjbar.datasets[0].bars[0].fillcolor = "green"; //bar 1
    myobjbar.datasets[0].bars[1].fillcolor = "orange"; //bar 2
    myobjbar.datasets[0].bars[2].fillcolor = "red"; //bar 3
    myobjbar.update();
}

score:92

as of v2, you can simply specify an array of values to correspond to a color for each bar via the backgroundcolor property:

datasets: [{
  label: "my first dataset",
  data: [20, 59, 80, 81, 56, 55, 40],
  backgroundcolor: ["red", "blue", "green", "blue", "red", "blue"], 
}],

this is also possible for the bordercolor, hoverbackgroundcolor, hoverbordercolor.

from the documentation on the bar chart dataset properties:

some properties can be specified as an array. if these are set to an array value, the first value applies to the first bar, the second value to the second bar, and so on.


Related Query

More Query from same tag