FattyPotatoes
FattyPotatoes

Reputation: 873

Google Charts - Change individual bar color

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'}}
                             });
}

Upvotes: 31

Views: 105281

Answers (10)

Kdon
Kdon

Reputation: 1235

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;
            }
          },

Upvotes: 0

Sameera Goutham
Sameera Goutham

Reputation: 57

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.

Upvotes: 4

Groom
Groom

Reputation: 11

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.

Upvotes: 1

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

Upvotes: 2

user3226750
user3226750

Reputation: 61

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";

Upvotes: 1

Josh Lopez
Josh Lopez

Reputation: 281

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
]);

Upvotes: 28

AFetter
AFetter

Reputation: 3614

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}}

Upvotes: 1

user1586747
user1586747

Reputation: 460

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
};

Upvotes: 42

Synchro
Synchro

Reputation: 37810

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}]
                             });
} ​

Upvotes: 6

codeandcloud
codeandcloud

Reputation: 55278

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}]
                             });
} 

Upvotes: 3

Related Questions