Home > front end >  Google Apps Script Chart.modify() changes chart background color
Google Apps Script Chart.modify() changes chart background color

Time:08-17

I'm using Apps Script to alter the axis min and max in some graphs, as described in this answer. I'm using a chart with numerical values, a bar chart, so I use this line of code:

var newChart = chart.modify().setOption("vAxis.maxValue", 30).setOption("vAxis.minValue", 0).build();

However, I use many custom colors in my charts, including eliminating a background color (so it just shows the color of the sheet cells, not the chart). When I run the script, the colors all get messed up in the chart. It reverts to white background, with a border and gridlines.

Here is a demo, with code embedded so you can see exactly what happens.

The chart on the right is the one the changes have been made to programmatically. Any insight into why this happens and how to avoid it would be greatly appreciated. Do I need to store the initial options?

CodePudding user response:

It seems there might be a bug regarding this behavior, I got the same result when testing. You can report the issue through here. As a workaround, you can try specifying the other options through the script. I added the background options to the script to make it transparent, remove gridlines and I was trying to remove the border from the chart with .setOption("backgroundColor", {'strokeWidth':0}) but it seems there is a bug related to this behavior and it has been already reported here.

function myFunction() {
  let sSht = SpreadsheetApp.getActiveSpreadsheet();
  let sheet = sSht.getSheets()[0];
  let charts = sheet.getCharts();
  let chart = charts[0];

  let newChart = chart.modify()
  .setOption("vAxis.maxValue", 5)
  .setOption("vAxis.minValue", 95)
  .setOption("backgroundColor", {'strokeWidth':0, 'fill': 'transparent'})
  .setOption("vAxes.0.minorGridlines.count", "0")
  .setOption("vAxis.gridlines.color", "transparent")
  .build();
  sheet.updateChart(newChart);
}
  • Related