Search code examples
google-apps-scriptgoogle-sheetsgoogle-sheets-api

Trying to generate Chart Line on google sheet but with info horizontaly


I have the following info in google sheet, but all documentation to create google chart is more about to read the info in a vertical way and i have code to read it vertical but as you see my info is horizontal...

enter image description here

My code only read vertical, how can i adapt it to my google sheet information?

function generarGraficoHorizontal() {
  var hoja = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var rango = hoja.getRange('A1:D10'); 
  var grafico = hoja.newChart()
    .setChartType(Charts.ChartType.LINE)
    .addRange(rango)
    .setPosition(2, 5, 0, 0)
    .build();

  hoja.insertChart(grafico);
}

Solution

  • You have data that is laid out "vertically" but your chart script assumes horizontal format.

    The "answer" is that you need to transpose your data. This can be done physically (there are plenty of examples on StackOverflow) OR you can do it within the ChartBuilder with the method:

    .setTransposeRowsAndColumns(true)

    Obviously the "virtual, ChartBuilder approach offers the ability to create the chart without copy/pasting your data.

    Also use .setNumHeaders(1) to create the the x-axis labels


    function generarGraficoHorizontal() {
      var hoja = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
      var rango = hoja.getRange('A1:D10'); 
      var grafico = hoja.newChart()
        .setChartType(Charts.ChartType.LINE)
        .addRange(rango)
        .setTransposeRowsAndColumns(true)
        .setPosition(2, 5, 0, 0)
        .build();
    
      hoja.insertChart(grafico);
    }
    

    setTransposeRowsAndColumns(true)

    .setNumHeaders(1)


    SAMPLE

    snapshot