AndrewLeonardi AndrewLeonardi - 3 months ago 21
HTML Question

Set background color for individual bars using ChartJS?

I'm attempting to model my bar chart after Chart.JS's example and have not been having any luck. This is what I'm tying to recreate:

http://www.chartjs.org/docs/#bar-chart-introduction

For whatever reason my bar's on the graph simply come out dark gray. I have been unable to fix this. My code is below. Does anyone know how I could change my code to fix this issue?

Thanks!

// bar chart data
var barData = {
labels : ["Counselor","Examiner","Rock","Seeker","Uniter"],

backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',

],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',

],
borderWidth: 1,


datasets : [
{
// fillColor : "#48A497",
// strokeColor : "#48A4D1",
data : [100, 200, 300, 400, 500, ]
}
]
}
// get bar chart canvas
var income = document.getElementById("income").getContext("2d");
// draw bar chart
new Chart(income).Bar(barData);

Answer

I think the issue is that the colors should be part of the dataset according to what I read in the official documentation link, try this:

var barData = {
                labels : ["Counselor","Examiner","Rock","Seeker","Uniter"],
                datasets : [{
                        // fillColor : "#48A497",
                        // strokeColor : "#48A4D1",
                        data : [100, 200, 300, 400, 500],
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.2)',
                            'rgba(54, 162, 235, 0.2)',
                            'rgba(255, 206, 86, 0.2)',
                            'rgba(75, 192, 192, 0.2)',
                            'rgba(153, 102, 255, 0.2)',
                            ],
                        borderColor: [
                            'rgba(255,99,132,1)',
                            'rgba(54, 162, 235, 1)',
                            'rgba(255, 206, 86, 1)',
                            'rgba(75, 192, 192, 1)',
                            'rgba(153, 102, 255, 1)',
                            ],
                        borderWidth: 1
                }]
            }

Fiddle example added: https://jsfiddle.net/hdr4uuLy/