Search code examples
angularchartsgoogle-visualization

Angular Google Charts: how to set different colors to columns in column chart


I am using Angular 9 + Google Charts via npm: npm install angular-google-charts

I want to set different colors to all columns in column charts but it's setting first color to all columns.

Did anybody encounter such problem or have any solution for setting different colors to columns in google column chart?

HTML:

<google-chart #chart
   [title]="title"
   [type]="type"
   [data]="data"
   [columns]="columnNames"
   [options]="options"
   [width]="width"
   [height]="height">
</google-chart>

TypeScript:

export class ColumnChartComponent[![enter image description here][1]][1] {
  title = 'Population (in millions)';
  type = 'ColumnChart';
  data = [
     ["2012", 900],
     ["2013", 1000],
     ["2014", 1170],
     ["2015", 1250],
     ["2016", 1530]
  ];
  columnNames = ['Year', 'Asia'];

  // chart options in which I am setting colors
  options = {
    colors: ['#5cb85c', '#f0ad4e', '#d9534f', '#5bc0de', '#f6c7b6'],
  };

  width = 550;
  height = 400;
}

Google Column Chart


Solution

  • Well, As there isn't a straight forward solution available get the different colors for all columns in angular-google-column-chart with nice colored legends. I came up with a trick cum workaround to get the desired result using stacked column chart to achive this.

    TypeScript:

    title = 'Resources Status Overview';
      type = 'ColumnChart';
    
    // => here is the trick. set single colored value for the column and rest to 0.
      data = [
        ["Ready", 500, 0, 0, 0],
        ["Pending", 0, 360, 0, 0],
        ["Deployed", 0, 0, 410, 0],
        ["Other", 0, 0, 0, 200],
      ];
    
      columnNames = ['Status', 'Ready', 'Pending', 'Deployed', 'Other'];
    
      options = {
        hAxis: {
          title: 'Status'
        },
        vAxis: {
          minValue: 0
        },
        isStacked: true,
        colors: ['#5cb85c', '#f0ad4e', '#d9534f', '#5bc0de']
      };
    
      width = 600;
      height = 400;
    

    It's a trick with the data set. In the stacked columns, set rest of the colors to 0 and keep the value in only for the matching color and you will get the nice column chart with legends. If you have limited data then this would be a nice solution for you.

    Column Chart with colors