Search code examples
google-apps-scriptgoogle-sheetsgoogle-visualizationpie-chart

How to display the values in a pie chart - Google Apps Script


So I have recently starting using apps script to create a dashboard that creates charts. However for the life of me, I can't get the pie slice text to show up. I've tried a lot of ways based on solutions I found online, but I think I now need someone's help to know if I'm doing something wrong in my code.

Here is the sheet with some dummy data.

https://docs.google.com/spreadsheets/d/1tPc0KU2uYuN4rO32tW-s6lql_IW57kbDUdSR8ZSkVXY/edit?usp=sharing

I had a lot of formatting for the texts and the labels etc, however I removed it all just to see if that was causing an issue. The PieSliceText, or data label, still won't show. Its super frustrating as I've been at it for a couple of days now. Hoping that someone will respond on the query!:)

And here is the code that I'm using:

  var sheet = SpreadsheetApp.getActiveSheet();
  var chartDataRange = sheet.getRange('G2:H5');   
  var pieChartTitle = SpreadsheetApp.getActiveSheet().getRange('I71').getValue();
  var pieChartBuilder = sheet.newChart()
     .addRange(chartDataRange)
     .setChartType(Charts.ChartType.PIE)
     .setOption('Slices',{0:{pieSliceText:'value'},1:{pieSliceText:'value'},2:{pieSliceText:'value'}})
     .setPosition(2,1,0,0)
     .setOption('title', pieChartTitle)
     .setOption('width',500).setOption('height',300)
     .setOption('pieHole',0.5)
     .build();
  
    sheet.insertChart(pieChartBuilder);
 }

Solution

  • If you are looking to display the values of the slices, try this:

    .setOption('pieSliceText', 'value')
    

    Code snippet:

    Value 350 does not appear because it is a very small slice compared to the other two.

    function createPieChart() {
      var sheet = SpreadsheetApp.getActiveSheet();
      var chartDataRange = sheet.getRange('G2:H5');   
      var pieChartTitle = SpreadsheetApp.getActiveSheet().getRange('I71').getValue();
      var pieChartBuilder = sheet.newChart()
         .addRange(chartDataRange)
         .setChartType(Charts.ChartType.PIE)
         .setOption('pieSliceText', 'value')
         .setPosition(2,1,0,0)
         .setOption('title', pieChartTitle)
         .setOption('width',500).setOption('height',300)
         .setOption('pieHole',0.5)
         .build();
        sheet.insertChart(pieChartBuilder);
     }
    

    label


    References:

    Visualization: Pie Chart