0
votes

How do you have each bar in a bar chart have a different color using angular-chartjs on the chartjs 2.0 branch?

My canvas looks like this:

<canvas class="chart chart-bar"
  chart-data="GBCC.setData" 
  chart-labels="GBCC.labels"
  chart-options="GBCC.options"
  chart-colors="GBCC.colors"
  height="68"
  width="300">
</canvas>

My GBCC controller looks like this:

this.labels = ['hello', 'world', 'foobar'];
this.setData = [[50, 20, 95]];
this.colors =  [ 
  '#DCDCDC', // light grey
  '#F7464A', // red
  '#46BFBD', // green
];
this.options = {
  scales: {
    yAxes: [{
      display: true,
      ticks: {
        beginAtZero: true,
        min: 0,
        max: 100,
        stepSize: 20
      }
    }]
  }
};

It will change all the bars to the first color in the array, but not use the other colors. Does any one know how to do this?

1

1 Answers

1
votes

If you are using this directive https://jtblin.github.io/angular-chart.js/, try the following:

this.color = [
  { backgroundColor: [
    '#DCDCDC', // light grey
    '#F7464A', // red
    '#46BFBD', // green
  ]};

This is from code review of the directive's convertColor and get color functions.

Line 238:

function convertColor (color) {
  if (typeof color === 'object' && color !== null) return color;
  if (typeof color === 'string' && color[0] === '#') return getColor(hexToRgb(color.substr(1)));
  return getRandomColor();
}

Line 249:

function getColor (color) {
  return {
    backgroundColor: rgba(color, 0.2),
    ...
  };`
}

And ChartJS's bar graph sample (http://www.chartjs.org/docs/#bar-chart-data-structure).

var data = {
    ...
    datasets: [
        {
            ...
            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)',
                'rgba(255, 159, 64, 0.2)'
            ],
            ...
        }
    ]
};

(And possibly an unwarranted hunch.)