Skip to content Skip to sidebar Skip to footer

How To Show Percentage In Google Barchart?

How to get the total number and percentage in google charts? I just want to get the percent and the number in the google charts, are there options that need to be set? Sample outp

Solution 1:

use the group method to find the total

var groupData = google.visualization.data.group(
  data,
  [{column: 0, modifier: function () {return'total'}, type:'string'}],
  [{column: 1, aggregation: google.visualization.data.sum, type: 'number'}]
);

and a DataView to add an 'annotation' column

see following working snippet...

google.charts.load('current', {
  callback: drawBasic,
  packages: ['corechart']
});

functiondrawBasic() {
  var data = google.visualization.arrayToDataTable([
    ['City', '2010 Population',],
    ['New York City, NY', 8175000],
    ['Los Angeles, CA', 3792000],
    ['Chicago, IL', 2695000],
    ['Houston, TX', 2099000],
    ['Philadelphia, PA', 1526000]
  ]);

  var groupData = google.visualization.data.group(
    data,
    [{column: 0, modifier: function () {return'total'}, type:'string'}],
    [{column: 1, aggregation: google.visualization.data.sum, type: 'number'}]
  );

  var formatPercent = new google.visualization.NumberFormat({
    pattern: '#,##0.0%'
  });

  var formatShort = new google.visualization.NumberFormat({
    pattern: 'short'
  });

  var view = new google.visualization.DataView(data);
  view.setColumns([0, 1, {
    calc: function (dt, row) {
      var amount =  formatShort.formatValue(dt.getValue(row, 1));
      var percent = formatPercent.formatValue(dt.getValue(row, 1) / groupData.getValue(0, 1));
      return amount + ' (' + percent + ')';
    },
    type: 'string',
    role: 'annotation'
  }]);

  var options = {
    annotations: {
      alwaysOutside: true
    },
    title: 'Population of Largest U.S. Cities',
    chartArea: {width: '50%'},
  };
  var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
  chart.draw(view, options);
}
<scriptsrc="https://www.gstatic.com/charts/loader.js"></script><divid="chart_div"></div>

Post a Comment for "How To Show Percentage In Google Barchart?"