Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify google sheet chart color based on cell value using app script

I want to create a dynamic chart that changes the color based on a cell value. I used the example in this answer but it only uses the first color I declared in the legend as seen in this image:

enter image description here

function modifyChart(sheet, newCssColor) {
  // Assume there is only one chart on this sheet.
  var sheet = SpreadsheetApp.getActive().getActiveSheet();
  const charts = sheet.getCharts();
  var array = [];

  var colorValues = sheet.getRange("G4:G6").getValues();
  for(var i = 0; i < colorValues.length; i++){
    array.push(colorValues[i][0]);
  }

Logger.log(colorValues);
  const barBuilder = charts[0].modify().asColumnChart().setColors(array);
  sheet.updateChart(barBuilder.build());
}

But here's exactly want to do:

If score <= 49 set bar color to red
Else if score >= 50 and score <= 89 set bar color to orange
else set bar color to green

Just like how the cell background changes because I set rules to it using Conditional Formatting.

Edit: Change the the cell range to match the sample

like image 421
jrwebapps Avatar asked Sep 15 '25 03:09

jrwebapps


1 Answers

Each of your categories is a series in your embedded chart. You want to set the style options of each series individually. Use setOption() and set the color options for each series.

For example:

EmbeddedChartBuilder.setOption('series.0.color', 'red').setOption('series.1.color', 'orange').setOption('series.2.color', 'green').build()

like image 112
Aerials Avatar answered Sep 16 '25 18:09

Aerials