Search code examples
google-apps-scriptchartsgoogle-visualization

Can't change line to bars - chart - Google script


I want to create a chart with the code below :

var sht=SpreadsheetApp.getActiveSheet();

  var chart = sht.newChart()
    .addRange(sht.getRange("B4:B11"))
    .addRange(sht.getRange("C4:C11"))
    .addRange(sht.getRange("D4:D11"))
    .addRange(sht.getRange("E4:E11"))
    .setChartType(Charts.ChartType.COMBO)
    .setPosition(2, 8, 0, 0)
    .setOption('title', 'Test')
    .setOption("series",{
      0:{type:'bars',color:'red'},
      1:{type:'bars',color:'blue'},
      2:{type:'line',color:'green'},
    })
    .build();

  sht.insertChart(chart);

With setOptions, I try to have two series of bars and one line, but I am not able : whatever I write, it always creates a chart with serie 0 type bars, series 1 and 2 type line.

Is there a reason?

EDIT : I also tried with code of a saved macro :

  var spreadsheet = SpreadsheetApp.getActive();
  var sheet = spreadsheet.getActiveSheet();
  
  chart = sheet.newChart()
  .asComboChart()
  .addRange(spreadsheet.getRange('B5:B11'))
  .addRange(spreadsheet.getRange('C4:C11'))
  .addRange(spreadsheet.getRange('D4:D11'))
  .addRange(spreadsheet.getRange('E4:E11'))
  .setOption('series.1.type', 'ColumnChart')
  .setOption('series.2.type', 'LineChart')
  .setPosition(4, 7, 0, 0)
  .build();

  sheet.insertChart(chart);

It does not work.

Thanks


Solution

  • I have replicated this issue and it looks like that there is a bug on the type: property in setOption() in which it does not apply to the combo chart, thus the output is always the default type which is bars, line, line (and line for each subsequent row).

    Sample Code and Output:

    function myFunction() {
      var sht=SpreadsheetApp.getActiveSheet();
    
      var chart = sht.newChart()
        .setChartType(Charts.ChartType.COLUMN)
        .addRange(sht.getRange("B4:F11"))
        .setPosition(2, 8, 0, 0)
        .setOption('title', 'Test')
    
        .build();
    
      sht.insertChart(chart);
    
      chart = chart.modify()
        .setChartType(Charts.ChartType.COMBO)
        .setOption("series",{
          0:{type:'area',color:'red'},
          1:{type:'line',color:'blue'},
          2:{type:'line',color:'green'},
          3:{type:'bars',color:'yellow'}
        })
        .build();
    
      sht.updateChart(chart);
    }
    

    enter image description here

    You can report this on the Issue Tracker so they can take a look at it, or follow this issue: https://issuetracker.google.com/issues/183272766