Google Charts - Change individual bar color
Asked Answered
L

10

31

With Google Charts bar graph, is it possible to to change the color of one bar. For example I'd like to make the 2006 data red (other bars are blue).

 function drawVisualization() {
            // Create and populate the data table.
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Year');
            data.addColumn('number', 'Sales');

            data.addRows(4);
            data.setValue(0, 0, '2004');
            data.setValue(0, 1, 1000);

            data.setValue(1, 0, '2005');
            data.setValue(1, 1, 1170);

  /* NEED TO MAKE THIS BAR RED? */
            data.setValue(2, 0, '2006');
            data.setValue(2, 1, 1400);

            data.setValue(3, 0, '2007');
            data.setValue(3, 1, 1030);


            chart = new google.visualization.BarChart(document.getElementById('visualization'));
            chart.draw(data, {width: 400, height: 240, title: 'Company Performance',
                              vAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
                             });
}
Lagrange answered 15/5, 2012 at 0:32 Comment(0)
S
42

Here is a code sample that changes the color. Note that the "colors" option accepts an array of strings.

var options = {
      title: 'Company Performance',
      hAxis: {title: 'Year', titleTextStyle: {color: 'red'}},
      colors: ['red','green'],
      is3D:true
};
Strikebound answered 9/8, 2012 at 7:0 Comment(4)
This seems to apply the first color in the array to all bars.Higley
@Higley did you find a fix for this? Looks like it's still the behaviour out of the box.Airedale
@nick-s no, I at the end I decided to switch to another library.Higley
@Higley hey which library you are using now? i am also stuck here to give multiple colors to the columnsAlienor
F
28

Refer to https://developers.google.com/chart/interactive/docs/gallery/columnchart#Colors

You can add { role: 'style' } to your data table. For all the columns that you want to have the same color, just specify an empty style ''. Then, on the column you want to be red, you could just specify 'red' or '#ff0000' or 'color: red', etc.

// example from Google
var data = google.visualization.arrayToDataTable([
    ['Element', 'Density', { role: 'style' }],
    ['Copper', 8.94, '#b87333'],            // RGB value
    ['Silver', 10.49, 'silver'],            // English color name
    ['Gold', 19.30, 'gold'],
    ['Platinum', 21.45, 'color: #e5e4e2' ], // CSS-style declaration
]);
Fragmentation answered 5/7, 2014 at 15:12 Comment(4)
I think this is the most correct answer. There's also the colour formatter, but it doesn't do max, so you'd have to pre-calculate the max, then set a threshold. google.visualization.ColorFormatThaxter
for some reason, this answer doesn't work even though it comes straight from the docsPlexiform
This is great for static tables, but if you need to change the values and the number of values dynamically I don't see how this could work. I tried putting a for loop in there but that doesn't seem to do it.Hua
best answer here. The documented way as well. +1Goddamned
B
6

As Naveen suggested, you should add another series in order to make it use a different colour, however if you add isStacked: true to your options it will draw bars on top of each other instead of next to each other and won't change their width or alignment, so it looks good. Try this:

function drawVisualization() {
  // Create and populate the data table.
  var data = new google.visualization.DataTable();
            data.addColumn('string', 'Year');
            data.addColumn('number', 'Sales');
            data.addColumn('number', 'SalesMax');

            data.addRows(4);
            data.setValue(0, 0, '2004');
            data.setValue(0, 1, 1000);
            data.setValue(0, 2, 0);

            data.setValue(1, 0, '2005');
            data.setValue(1, 1, 1170);
            data.setValue(1, 2, 0);

  /* NEED TO MAKE THIS BAR RED? */
            data.setValue(2, 0, '2006');
            data.setValue(2, 1, 0);
            data.setValue(2, 2, 1400);

            data.setValue(3, 0, '2007');
            data.setValue(3, 1, 1030);
            data.setValue(3, 2, 0);


            var chart = new google.visualization.BarChart(document.getElementById('visualization'));
  chart.draw(data, {isStacked: true, width: 400, height: 240, title: 'Company Performance',
                              vAxis: {title: 'Year', titleTextStyle: {color: 'red'}},
                              series: [{color: 'blue', visibleInLegend: true}, {color: 'red', visibleInLegend: false}]
                             });
} ​
Belvabelvedere answered 31/5, 2012 at 15:24 Comment(4)
Excellent! I know this was a long time ago, but I've just been struggling with this same problem and your solution works a treat. Thanks :)Bostwick
-1. This is copy-n-pasted from naveen's answer with one tiny (though important) addition. Should've just commented on/edited the original answer.Deboer
Well it's mostly copy'n'pasted from the original question. I did credit @naveen for the extra series idea and I wanted to provide a complete working script that wouldn't fit in a comment, and a complete answer isn't appropriate for a comment anyway. Nothing stopping you from +1'ing both answers.Belvabelvedere
Thank's @Synchro. Your answer helped me to change colors from stacked columns. Perfectly.Arathorn
L
4
var options = {

      colors: ['red','green', 'purple']

};

colors parameter will only accept arrays if we are using this we have to make sure we are adding color for all the elements.

Lambency answered 3/11, 2019 at 12:32 Comment(0)
F
3

You could always insert an extra column and so it will have different color. Thats all that can be done I guess.

function drawVisualization() {
  // Create and populate the data table.
  var data = new google.visualization.DataTable();
            data.addColumn('string', 'Year');
            data.addColumn('number', 'Sales');
            data.addColumn('number', 'SalesMax');

            data.addRows(4);
            data.setValue(0, 0, '2004');
            data.setValue(0, 1, 1000);
            data.setValue(0, 2, 0);

            data.setValue(1, 0, '2005');
            data.setValue(1, 1, 1170);
            data.setValue(1, 2, 0);

  /* NEED TO MAKE THIS BAR RED? */
            data.setValue(2, 0, '2006');
            data.setValue(2, 1, 0);
            data.setValue(2, 2, 1400);

            data.setValue(3, 0, '2007');
            data.setValue(3, 1, 1030);
            data.setValue(3, 2, 0);


            var chart = new google.visualization.BarChart(document.getElementById('visualization'));
            chart.draw(data, {width: 400, height: 240, title: 'Company Performance',
                              vAxis: {title: 'Year', titleTextStyle: {color: 'red'}},
                              series: [{color: 'blue', visibleInLegend: true}, {color: 'red', visibleInLegend: false}]
                             });
} 
Fro answered 15/5, 2012 at 1:8 Comment(2)
I actually tried that and hoped to find a cleaner way because it changes the alignment and width of bars.Lagrange
@FattyPotatoes: very true. But I think this is the only option.Fro
T
2

Here's an example of the above tips

google.charts.load('current', { packages: ['corechart', 'bar'] })
google.charts.setOnLoadCallback(drawStacked)

function mt_rand (min, max) {
  var argc = arguments.length
  if (argc === 0) {
    min = 0
    max = 2147483647
  } else if (argc === 1) {
    throw new Error('Warning: mt_rand() expects exactly 2 parameters, 1 given')
  }
  return Math.floor(Math.random() * (max - min + 1)) + min
}

function dechex (d) {
  var hex = Number(d).toString(16)
  hex = '000000'.substr(0, 6 - hex.length) + hex
  return hex
}

function str_pad (str) {
  str += ''
  while (str.length < 3) {
    str = str + str
  }
  return str
}

function random_color_part () {
  // return str_pad( dechex( mt_rand( 0, 255 ) ), 2, '0', 1);
  return mt_rand(0, 255)
}

function random_color () {
  return 'rgb(' + random_color_part() + ',' + random_color_part() + ',' + random_color_part() + ')'
}

let $color = random_color()
// alert($color);

function drawStacked () {
  // var data = new google.visualization.DataTable();

  var data = google.visualization.arrayToDataTable([
    ['Element', 'Density', { role: 'style' }],
    ['cor-glenio-aleatoria', 8.94, random_color()], // RGB value
    ['cor-arlei-aleatoria', 10.49, random_color()], // English color name
    ['outra cor', 19.30, random_color()],

    ['outra cor fixa', 21.45, 'color: #e5e4e2' ] // CSS-style declaration
  ])

  var options = {
    title: 'Motivation and Energy Level Throughout the Day',
    isStacked: true,
    hAxis: {
      title: 'Time of Day',
      format: 'h:mm a',
      viewWindow: {
        min: [7, 30, 0],
        max: [17, 30, 0]
      }
    },
    vAxis: {
      title: 'Rating (scale of 1-10)'
    }
  }

  var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'))
  chart.draw(data, options)
}
https://jsfiddle.net/zeh3pn6d/2
Tympanist answered 13/6, 2019 at 21:45 Comment(0)
T
1

series Array of objects, or object with nested objects

An array of objects, each describing the format of the corresponding series in the chart. To use default values for a series, specify an empty object {}. If a series or a value is not specified, the global value will be used. Each object supports the following properties:

color - The color to use for this series. Specify a valid HTML color string. targetAxisIndex - Which axis to assign this series to, where 0 is the default axis, and 1 is the opposite axis. Default value is 0; set to 1 to define a chart where different series are rendered against different axes. At least one series much be allocated to the default axis. You can define a different scale for different axes.

visibleInLegend - A boolean value, where true means that the series should have a legend entry, and false means that it should not. Default is true. You can specify either an array of objects, each of which applies to the series in the order given, or you can specify an object where each child has a numeric key indicating which series it applies to. For example, the following two declarations are identical, and declare the first series as black and absent from the legend, and the fourth as red and absent from the legend:

series: {0:{color: 'black', visibleInLegend: false}, 3:{color: 'red', visibleInLegend: false}}
Tuesday answered 19/8, 2013 at 3:0 Comment(0)
B
1

i solve this problem using role style technique now for charts that generate dynamic data i used a random function to generate color

    function random_color_part() {
return str_pad( dechex( mt_rand( 0, 255 ) ), 2, '0', STR_PAD_LEFT);
}

function random_color() {
return random_color_part() . random_color_part() . random_color_part();
}
then simply
$color=random_color();
print "['$rows[1]',$rows[2],'#$color'],\n";
Bellied answered 4/4, 2017 at 13:29 Comment(0)
M
1

Just leaving this here, in case somebody else runs in to the same issue as me:

I had a similar problem where I couldn't change the color of specific bars in a bar-chart. I did as the documentation said, and tried some of the answers here, but nothing worked.

Turned out, I just needed to change google.charts.Bar to google.visualization.ColumnChart.

Muck answered 3/9, 2019 at 8:33 Comment(0)
O
0

Another way that worked for me is to use the ternery operator on colorFn...

          colorFn: (series, _) {
            if (series.highScore) {
              return charts.MaterialPalette.green.shadeDefault;
            } else {
              return charts.MaterialPalette.gray.shadeDefault;
            }
          },
Orate answered 31/3, 2022 at 8:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.