google-sheetsgoogle-apps-scriptcharts

Stacked column chart to use column A as header in App Script


I have this table and the chart I want as below:

enter image description here

To acheive this I have to switch rows/columns, and use column A as headers.

However I cannot find the corresponding command for the checkbox "Use column A as headers".

This is my script:

function myFunction() {
  const sheetTest = SpreadsheetApp.getActive().getSheetByName("test");

  const numRows = sheetTest.getLastRow();     // e.g. 9
  const numCols = sheetTest.getLastColumn();  // e.g. 3

  const chartRange = sheetTest.getRange(1, 1, numRows, numCols);
  const chart = sheetTest.newChart()
    .asColumnChart()
    .addRange(chartRange)
    .setStacked()
    .setPosition(1, 4, 0, 0)
    .setTransposeRowsAndColumns(true)
    .build();

  sheetTest.insertChart(chart);
}

This is what it produces, just one more step and it'd be perfect as you can see the headers are missing

enter image description here


Solution

  • In your script, how about using setNumHeaders as follows?

    Modified script:

    function myFunction() {
      const sheetTest = SpreadsheetApp.getActive().getSheetByName("test");
    
      const numRows = sheetTest.getLastRow();     // e.g. 9
      const numCols = sheetTest.getLastColumn();  // e.g. 3
    
      const chartRange = sheetTest.getRange(1, 1, numRows, numCols);
      const chart = sheetTest.newChart()
        .asColumnChart()
        .addRange(chartRange)
        .setStacked()
        .setPosition(1, 4, 0, 0)
        .setTransposeRowsAndColumns(true)
        .setNumHeaders(1) // Added
        .build();
    
      sheetTest.insertChart(chart);
    }
    

    Testing:

    When this modified script is used, the following result is obtained.

    enter image description here

    Reference