Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying percentages in stacked bar Google Charts

Tags:

// Display google stacked bar chart
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
    calc: "stringify",
    sourceColumn: 1,
    type: "string",
role: "annotation"
},
2]);

Below is the picture of stacked bar chart I have.

enter image description here

I am not able to display the percentage on the green bar but not on the red bar. The current value in the green bar is not a percentage value.

like image 509
Skylark Jacobs Avatar asked Nov 17 '16 06:11

Skylark Jacobs


1 Answers

need an annotation column for each series...

var view = new google.visualization.DataView(data);
view.setColumns([0,
  // series 0
  1, {
    calc: "stringify",
    sourceColumn: 1,
    type: "string",
    role: "annotation"
  },
  // series 1
  2, {
    calc: "stringify",
    sourceColumn: 2,
    type: "string",
    role: "annotation"
  }
]);

EDIT

to format the annotation value as a percentage

replace the "stringify" function with a custom function

use a NumberFormat formatter to format the value

see following working snippet...

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

function drawSeriesChart() {
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Month');
  data.addColumn('number', 'Category A');
  data.addColumn('number', 'Category B');
  data.addRows([
    ['Sep', 100, 190],
    ['Oct', 220, 178]
  ]);

  var formatPercent = new google.visualization.NumberFormat({
    pattern: '#,##0.0%'
  });
  
  var view = new google.visualization.DataView(data);
  view.setColumns([0,
    // series 0
    1, {
      calc: function (dt, row) {
        return dt.getValue(row, 1) + ' (' + formatPercent.formatValue(dt.getValue(row, 1) / (dt.getValue(row, 1) + dt.getValue(row, 2))) + ')';
      },
      type: "string",
      role: "annotation"
    },
    // series 1
    2, {
      calc: function (dt, row) {
        return dt.getValue(row, 2) + ' (' + formatPercent.formatValue(dt.getValue(row, 2) / (dt.getValue(row, 1) + dt.getValue(row, 2))) + ')';
      },
      type: "string",
      role: "annotation"
    }
  ]);

  var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
  chart.draw(view, {
    isStacked: 'percent'
  });
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

UPDATED SCREENSHOT For reference to my COMMENT

like image 135
WhiteHat Avatar answered Sep 26 '22 13:09

WhiteHat