emir
emir

Reputation: 1406

How to change bar color acording to label value in chartjs

I need to use bars in chartjs and I need all bars to be in one color, and just one in the middle to be of other color. It would be the best if I could create value range according to which the specific color would be used.

http://s24.postimg.org/4jg17tm5h/graf.png

I have painted this one bar manually with this command

myLine.datasets[0].bars[50].fillColor = "red";

but I need it to be automatically, to pick one value and to chose color by its limits. Is it possible?

Upvotes: 0

Views: 1878

Answers (2)

emir
emir

Reputation: 1406

I have used part of your solution and solved problem

        for (var i = 0; i < myLine.datasets[0].bars.length; i++) {
        console.log(myLine.datasets[0].bars[i].value);
        if(myLine.datasets[0].bars[i].value < 10) {
            myLine.datasets[0].bars[i].fillColor = "red";
        } else if (myLine.datasets[0].bars[i].value > 20) {
            myLine.datasets[0].bars[i].fillColor = "yellow";
        }
    }

This is what I need, thanks, I didn't know how to access values of bars.

Upvotes: 0

dhouty
dhouty

Reputation: 1989

Check out the getBarsAtEvent method in the documentation.

Here is an example of how you could use it, though you will likely have to modify this to your specific needs:

canvas.onmousemove = function(evt) {
    var bars = chart.getBarsAtEvent(evt);
    for (var i = 0; i < bars.length; i++) {
        setColor(bars[i]);
    }
};

function setColor(bar) {
    if (bar.value < 10) {
        bar.fillColor = "red";
    } else if (bar.value < 20) {
        bar.fillColor = "yellow";
    } else {
        bar.fillColor = "green";
   }
}

Upvotes: 1

Related Questions