google stacked bar chart do not want to display 0 bar - charts

In a google stacked bar chart is there any way to have it not display a bar with a zero value?
I do not want the thin red line on the first bar or the hover to show.
Here is my code:
var data = google.visualization.arrayToDataTable([
['Class', 'Cost', 'Savings', { role: 'annotation' } ],
['Current State Run', 140999460, 0, ''],
['Total Future State Run', 109351526, 31647934, '']
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2,
{ calc: formatter,
sourceColumn: 2,
type: "string",
role: "annotation" },
3]);
function formatter(dataTable, row) {
if (data.getValue(row, 2))
return parseInt(data.getValue(row, 2)).toLocaleString()
else
return '';
}

convert the zero value to null,
this will hide the line and tooltip.
if needed, you can use a DataView and calculated columns,
to dynamically change the zeroes to null
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Class', 'Cost', 'Savings'],
['Current State Run', 140999460, 0],
['Total Future State Run', 109351526, 31647934]
]);
var view = new google.visualization.DataView(data);
var viewCols = [0];
for (var i = 1; i < data.getNumberOfColumns(); i++) {
addCalcs(i);
}
view.setColumns(viewCols);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
var options = {
isStacked: true
};
chart.draw(view, options);
function addCalcs(col) {
viewCols.push({
calc: function (dt, row) {
return getNullValue(dt, row, col);
},
label: data.getColumnLabel(col),
type: data.getColumnType(col)
});
viewCols.push({
calc: function (dt, row) {
return formatter(dt, row, col);
},
type: 'string',
role: 'annotation'
});
}
function formatter(dataTable, row, col) {
if (data.getValue(row, col)) {
return parseInt(data.getValue(row, col)).toLocaleString()
} else {
return '';
}
}
function getNullValue(dataTable, row, col) {
var value = dataTable.getValue(row, col);
if (value === 0) {
return null;
}
return value;
}
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Related

Google charts show unformatted value in tooltip

I have a formatted label displayed on the bars on my chart.
This value also gets formatted in the tooltip. Is there a way to show the unformatted, raw value on the tooltip, while keeping it formatted on the label?
https://jsfiddle.net/67u052kL/1/
var formatter = new google.visualization.NumberFormat({
pattern: 'short'
});
formatter.format(data, 1);
formatter.format(data, 3);
only format the annotation value.
to accomplish, use a custom function for the annotation role, instead of the 'stringify' function.
and you can use the formatter's formatValue method, to format a single value.
view.setColumns([0, 1, {
calc: function (dt, row) {
return formatter.formatValue(dt.getValue(row, 1));
},
type: 'string',
role: 'annotation'
}, 2, 3, {
calc: function (dt, row) {
return formatter.formatValue(dt.getValue(row, 3));
},
type: 'string',
role: 'annotation'
}]);
see following working snippet...
google.charts.load('50', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Team' , 'Actual', { role: 'style'}, 'Target'],
['Alpha' , 35976, 'color: #F6931D', 90000],
['Beta' , 40542, 'color: #FDCB2F', 104167],
['Gamma' , 111227, 'color: #8AC659', 205000],
['Delta' , 238356, 'color: #32A242', 205000],
['Epsilon', 170555, 'color: #3A81C2', 354167]
]);
var formatter = new google.visualization.NumberFormat({
pattern: 'short'
});
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: function (dt, row) {
return formatter.formatValue(dt.getValue(row, 1));
},
type: 'string',
role: 'annotation'
}, 2, 3, {
calc: function (dt, row) {
return formatter.formatValue(dt.getValue(row, 3));
},
type: 'string',
role: 'annotation'
}]);
var options = {
title: {position: 'none'},
orientation: 'vertical',
animation: {duration : 600, startup: 'true', easing:'out'},
annotations: {highContrast: 'true'},
legend: {position: 'none'},
// theme: 'material',
chartArea:{top:5, right: 25, width: '70%', height: '90%'},
hAxis: {format:'short'},
// vAxis: {textPosition:'in'},
// bar: {groupWidth: '90%'},
seriesType: 'bars',
series: {
1: {type: 'bars', color: 'lightgray'}
}
};
var chart = new google.visualization.ComboChart(document.getElementById('chartContentPane'));
chart.draw(view, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chartContentPane"></div>

google charts bar horizontal move annotation position to center of stacked chart

I am using Google Chart's column graph chart. The chart is a stacked column chart with annotations for every data point of the stacked column. The annotation are at the right of the inside of the bar but I would like them to be centered inside of the bar.
I'm looking this page with a begin solution. This page
with an function "moveAnnotations()", but I can't get the code for a horizontal bar chart.
Thanks for your help, i'm lost. :(
/** Valeurs pour le graph bar 1 */
var data_graph_bar_1 = [
['Years', 'Beer & other', 'Water', 'CSD', 'Sensitive'],
['2014', 71, 56, 79, 59],
['2019', 70, 74, 75, 65]
];
// Load the Visualization API and the corechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(function(){drawChart(data_graph_bar_1)});
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart(datas) {
var data = google.visualization.arrayToDataTable(datas);
var view = new google.visualization.DataView(data);
view.setColumns([0,
1, {
calc: function (dt, row) {
return dt.getValue(row, 1);
},
type: "number",
role: "annotation"
},
2, {
calc: function (dt, row) {
return dt.getValue(row, 2);
},
type: "number",
role: "annotation"
},
3, {
calc: function (dt, row) {
return dt.getValue(row, 3);
},
type: "number",
role: "annotation"
},
4, {
calc: function (dt, row) {
return dt.getValue(row, 4);
},
type: "number",
role: "annotation"
},
{
calc: function (dt, row) {
return 0;
},
label: "Total",
type: "number",
},
{
calc: function (dt, row) {
return dt.getValue(row, 1) + dt.getValue(row, 2)+ dt.getValue(row, 3)+ dt.getValue(row, 4);
},
type: "number",
role: "annotation"
}
]);
var options = {
height: 130,
colors: ['#B4CC00', '#3399FF', '#E64B00','#FF8B00'],
legend: 'none',
bar: { groupWidth: '75%' },
isStacked: true,
displayAnnotations: true,
annotations: {
textStyle: {
// The color of the text.
color: '#000000',
fontSize: 15
},
},
hAxis: {
gridlines: {
count: 0
},
textPosition: 'none',
textStyle : {
fontSize: 15
}
},
vAxis: {
textStyle: {
bold: true,
fontSize: '20',
}
},
chartArea:{
left:50,
},
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(view, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
instead of adjusting the 'y' attribute of the label,
we just need to adjust the 'x' attribute...
first, we need to locate the annotation label.
here, we loop all the row and columns, then use the value to find the label.
we exclude labels with black color, because these are shown in the tooltip,
we do not want to move those.
for (var r = 0; r < data.getNumberOfRows(); r++) {
for (var c = 1; c < data.getNumberOfColumns(); c++) {
var labels = chart.getContainer().getElementsByTagName('text');
Array.prototype.forEach.call(labels, function(label, index) {
if ((label.textContent === data.getValue(r, c).toFixed(0)) &&
(label.getAttribute('fill') !== '#000000')) {
barBounds = chartLayout.getBoundingBox('bar#' + (c - 1) + '#' + r);
xAdj = (barBounds.width / 2);
label.setAttribute('x', barBounds.left + xAdj);
label.setAttribute('text-anchor', 'middle');
}
});
}
}
see following working snippet...
var data_graph_bar_1 = [
['Years', 'Beer & other', 'Water', 'CSD', 'Sensitive'],
['2014', 71, 56, 79, 59],
['2019', 70, 74, 75, 65]
];
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(function(){drawChart(data_graph_bar_1)});
function drawChart(datas) {
var data = google.visualization.arrayToDataTable(datas);
var view = new google.visualization.DataView(data);
view.setColumns([0,
1, {
calc: function (dt, row) {
return dt.getValue(row, 1);
},
type: "number",
role: "annotation"
},
2, {
calc: function (dt, row) {
return dt.getValue(row, 2);
},
type: "number",
role: "annotation"
},
3, {
calc: function (dt, row) {
return dt.getValue(row, 3);
},
type: "number",
role: "annotation"
},
4, {
calc: function (dt, row) {
return dt.getValue(row, 4);
},
type: "number",
role: "annotation"
},
{
calc: function (dt, row) {
return 0;
},
label: "Total",
type: "number",
},
{
calc: function (dt, row) {
return dt.getValue(row, 1) + dt.getValue(row, 2)+ dt.getValue(row, 3)+ dt.getValue(row, 4);
},
type: "number",
role: "annotation"
}
]);
var options = {
height: 130,
colors: ['#B4CC00', '#3399FF', '#E64B00','#FF8B00'],
legend: 'none',
bar: { groupWidth: '75%' },
isStacked: true,
displayAnnotations: true,
annotations: {
textStyle: {
// The color of the text.
color: '#000000',
fontSize: 15
},
},
hAxis: {
gridlines: {
count: 0
},
textPosition: 'none',
textStyle : {
fontSize: 15
}
},
vAxis: {
textStyle: {
bold: true,
fontSize: '20',
}
},
chartArea:{
left:50,
},
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'ready', function () {
var observer = new MutationObserver(moveAnnotations);
observer.observe(chart.getContainer(), {
childList: true,
subtree: true
});
});
function moveAnnotations() {
var chartLayout = chart.getChartLayoutInterface();
var barBounds;
var xAdj;
for (var r = 0; r < data.getNumberOfRows(); r++) {
for (var c = 1; c < data.getNumberOfColumns(); c++) {
var labels = chart.getContainer().getElementsByTagName('text');
Array.prototype.forEach.call(labels, function(label, index) {
if ((label.textContent === data.getValue(r, c).toFixed(0)) && (label.getAttribute('fill') !== '#000000')) {
barBounds = chartLayout.getBoundingBox('bar#' + (c - 1) + '#' + r);
xAdj = (barBounds.width / 2);
label.setAttribute('x', barBounds.left + xAdj);
label.setAttribute('text-anchor', 'middle');
}
});
}
}
}
chart.draw(view, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
EDIT
if there are more than one annotations with the same value,
then we need to add another condition.
similar to getting the bar bounds from the chart's interface,
we can get the annotation bounds.
labelBounds = chartLayout.getBoundingBox('annotationtext#' + (c - 1) + '#' + r + '#0');
and since the initial alignment of the annotation is to the right,
or text-anchor="end",
this means the difference between the 'x' attribute on the <text> element and the left property of the bounds will equal the width of the bounds.
we can use this difference to ensure we have the correct annotation before moving it.
((parseFloat(label.getAttribute('x')) - labelBounds.left) === labelBounds.width)
see following working snippet...
var data_graph_bar_1 = [
['Years', 'Beer & other', 'Water', 'CSD', 'Sensitive'],
['2014', 71, 56, 74, 59],
['2019', 70, 74, 75, 65]
];
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(function(){drawChart(data_graph_bar_1)});
function drawChart(datas) {
var data = google.visualization.arrayToDataTable(datas);
var view = new google.visualization.DataView(data);
view.setColumns([0,
1, {
calc: function (dt, row) {
return dt.getValue(row, 1);
},
type: "number",
role: "annotation"
},
2, {
calc: function (dt, row) {
return dt.getValue(row, 2);
},
type: "number",
role: "annotation"
},
3, {
calc: function (dt, row) {
return dt.getValue(row, 3);
},
type: "number",
role: "annotation"
},
4, {
calc: function (dt, row) {
return dt.getValue(row, 4);
},
type: "number",
role: "annotation"
},
{
calc: function (dt, row) {
return 0;
},
label: "Total",
type: "number",
},
{
calc: function (dt, row) {
return dt.getValue(row, 1) + dt.getValue(row, 2)+ dt.getValue(row, 3)+ dt.getValue(row, 4);
},
type: "number",
role: "annotation"
}
]);
var options = {
height: 130,
colors: ['#B4CC00', '#3399FF', '#E64B00','#FF8B00'],
legend: 'none',
bar: { groupWidth: '75%' },
isStacked: true,
displayAnnotations: true,
annotations: {
textStyle: {
// The color of the text.
color: '#000000',
fontSize: 15
},
},
hAxis: {
gridlines: {
count: 0
},
textPosition: 'none',
textStyle : {
fontSize: 15
}
},
vAxis: {
textStyle: {
bold: true,
fontSize: '20',
}
},
chartArea:{
left:50,
},
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'ready', function () {
var observer = new MutationObserver(moveAnnotations);
observer.observe(chart.getContainer(), {
childList: true,
subtree: true
});
});
function moveAnnotations() {
var chartLayout = chart.getChartLayoutInterface();
var barBounds;
var xAdj;
for (var r = 0; r < data.getNumberOfRows(); r++) {
for (var c = 1; c < data.getNumberOfColumns(); c++) {
var labels = chart.getContainer().getElementsByTagName('text');
Array.prototype.forEach.call(labels, function(label, index) {
labelBounds = chartLayout.getBoundingBox('annotationtext#' + (c - 1) + '#' + r + '#0');
barBounds = chartLayout.getBoundingBox('bar#' + (c - 1) + '#' + r);
if ((label.textContent === data.getValue(r, c).toFixed(0)) && (label.getAttribute('fill') !== '#000000') && ((parseFloat(label.getAttribute('x')) - labelBounds.left) === labelBounds.width)) {
xAdj = (barBounds.width / 2);
label.setAttribute('x', barBounds.left + xAdj);
label.setAttribute('text-anchor', 'middle');
}
});
}
}
}
chart.draw(view, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Offset tick labels to center between ticks on horizontal bar chart

I am creating a horizontal bar chart using Google charts and I want to position the horizontal axis tick labels between ticks (offset tick label to the right by half a tick). There is also no guarantee that each label will be the same number of characters. Is there any functionality to achieve this?
This is my function for creating the chart
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Performance", "Level", { role: "style" }],
["PL", 1.01, "#5aa66d"]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{
calc: function (dt, rowIndex) { return 'PL=' + (dt.getValue(rowIndex, 1)).toString()} ,
sourceColumn: 1,
type: "string",
role: "annotation"
},
2]);
var options = {
width: 600,
height: 100,
bar: { groupWidth: "80%" },
legend: { position: "none" },
hAxis: {
minValue: 0,
maxValue: 3,
ticks: [
{ v: 0, f: 'Col1' },
{ v: 1, f: 'Col2' },
{ v: 2, f: 'Col3' },
{ v: 3, f: 'Col4' }
]
}
};
var chart = new google.visualization.BarChart(document.getElementById("barchart_values"));
chart.draw(view, options);
}
This is the chart currently
https://imgur.com/LvQEbtY
and this is what I want to achieve:
https://imgur.com/hwvIOG2
EDIT:
For ideas, right before chart.draw I add an event listener and find all the text tags and modify the 'x' attribute to re-position the tick labels. This works, but it also affects the on-bar data label which is a problem.
google.visualization.events.addListener(chart, 'ready', function () {
var elements = document.getElementById("barchart_values").getElementsByTagName("text");
for (var i = 0; i < elements.length; i++) {
elements[i].setAttribute('x', (Number(elements[i].getAttribute('x')) + (chart.getChartLayoutInterface().getBoundingBox('chartarea').width / 4 / 2))); //chart width / tick count / 2
}
});
first, we won't be able to offset the grid lines and use the ticks option.
let's offset the grid lines by making the major transparent and the minor visible.
we can also offset the baseline by setting to a negative value.
baseline: -0.5,
minorGridlines: {
color: '#cccccc',
count: 1
},
gridlines: {
color: 'transparent',
count: 4
},
then, in order to have custom tick labels, we can use your original idea to change them manually.
just need a unique attribute to separate them from the bar labels.
here, the text-anchor attribute is used.
if (elements[i].getAttribute('text-anchor') === 'middle') {
elements[i].textContent = 'Col' + parseInt(elements[i].textContent) + 1;
}
see following working snippet...
google.charts.load('current', {
packages:['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
["Performance", "Level", { role: "style" }],
["PL", 1.01, "#5aa66d"]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: function (dt, rowIndex) { return 'PL=' + (dt.getValue(rowIndex, 1)).toString()} ,
sourceColumn: 1,
type: "string",
role: "annotation"
}, 2]);
var options = {
width: 600,
height: 100,
bar: { groupWidth: "80%" },
legend: { position: "none" },
hAxis: {
baseline: -0.5,
minorGridlines: {
color: '#cccccc',
count: 1
},
gridlines: {
color: 'transparent',
count: 4
},
minValue: 0,
maxValue: 3,
}
};
var chart = new google.visualization.BarChart(document.getElementById("barchart_values"));
google.visualization.events.addListener(chart, 'ready', function () {
var elements = document.getElementById("barchart_values").getElementsByTagName("text");
for (var i = 0; i < elements.length; i++) {
if (elements[i].getAttribute('text-anchor') === 'middle') {
elements[i].textContent = 'Col' + (parseInt(elements[i].textContent) + 1);
}
}
});
chart.draw(view, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="barchart_values"></div>
the above will ensure all the labels remain visible, just simply moving them, could cause them to be pushed off the visible portion of the chart.

Label Values and Total in Google Visualization Stacked Bar Chart

I am trying to display the value of each bar and then the total value of all bars in a stacked bar chart The problem is, I get the last bar's value and the total both outside the bar. If I do not show the total, I get the value inside the bar. Using the code below the the last two annotations are outside the second bar even when the second bar is long enough to show its label.
<html>
<head>
<base target="_top">
</head>
<body>
<h3>Registrations</h3>
<div id="registrations_chart"></div>
</body>
</html>
<script>
google.charts.load('current', {'packages':['corechart', 'bar', 'gauge', 'table']});
google.charts.setOnLoadCallback(drawStackedBar);
function drawStackedBar() {
var myHeight = 350;
var data = new google.visualization.DataTable();
data.addColumn('string', 'Registrations');
data.addColumn('number', 'Regular');
data.addColumn('number', 'Work Study');
data.addRows([
['Adult', 20, 12],
['Teen', 3, 0]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0,
1, {
calc: function (dt, row) {
return dt.getValue(row, 1);
},
type: "number",
role: "annotation"
},
2, {
calc: function (dt, row) {
return dt.getValue(row, 2);
},
type: "number",
role: "annotation"
},
// series 1
{
calc: function (dt, row) {
return dt.getValue(row, 1) + dt.getValue(row, 2);
},
type: "number",
role: "annotation"
}
]);
var options = {
animation:{
duration: 1000,
easing: 'out',
startup: true
},
title: 'Registrations',
backgroundColor: 'transparent',
height: myHeight, width: 500,
legend: {
position: 'top',
maxLines: 3
},
bar: { groupWidth: '75%' },
isStacked: true
};
var chart = new google.visualization.BarChart(document.getElementById('registrations_chart'));
chart.draw(view, options);
}
</script>
If I removed the last option in the setColumns to make that section read as follows:
view.setColumns([0,
1, {
calc: function (dt, row) {
return dt.getValue(row, 1);
},
type: "number",
role: "annotation"
},
2, {
calc: function (dt, row) {
return dt.getValue(row, 2);
},
type: "number",
role: "annotation"
},
// series 1
{
calc: function (dt, row) {
return dt.getValue(row, 1) + dt.getValue(row, 2);
},
type: "number",
role: "annotation"
}
]);
I get the labels where I want them without the Total, as shown below
What I am after is to add the Total to the end and the Labels consistently inside as shown below:
I have tried too many methods to remember or list here, but am not getting the Total at the end. How can I get this last Label to appear and keep the others inside the bar when they will fit there? Note that I have made the red bar longer than the blue one and the numbers still displayed as shown.
you could add another series column for the total
then hide it from the chart with the following options...
enableInteractivity: false,
tooltip: "none",
visibleInLegend: false
this will allow the annotations from the other values to perform normally
the total annotation will always show outside,
but need to adjust a few options to keep it from overwriting others...
annotations: {
stem: {
color: "transparent",
length: 28
},
textStyle: {
color: "#000000",
}
},
see following working snippet...
google.charts.load('50', {
packages:['corechart']
}).then(function () {
var myHeight = 350;
var data = new google.visualization.DataTable();
data.addColumn('string', 'Registrations');
data.addColumn('number', 'Regular');
data.addColumn('number', 'Work Study');
data.addRows([
['Adult', 20, 12],
['Teen', 3, 0]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0,
1, {
calc: function (dt, row) {
return dt.getValue(row, 1);
},
type: "number",
role: "annotation"
},
2, {
calc: function (dt, row) {
return dt.getValue(row, 2);
},
type: "number",
role: "annotation"
},
{
calc: function (dt, row) {
return 0;
},
label: "Total",
type: "number",
},
{
calc: function (dt, row) {
return dt.getValue(row, 1) + dt.getValue(row, 2);
},
type: "number",
role: "annotation"
}
]);
var options = {
animation:{
duration: 1000,
easing: 'out',
startup: true
},
title: 'Registrations',
backgroundColor: 'transparent',
height: myHeight, width: 500,
legend: {
position: 'top',
maxLines: 3
},
bar: { groupWidth: '75%' },
isStacked: true,
series: {
2: {
annotations: {
stem: {
color: "transparent",
length: 28
},
textStyle: {
color: "#000000",
}
},
enableInteractivity: false,
tooltip: "none",
visibleInLegend: false
}
}
};
var chart = new google.visualization.BarChart(document.getElementById('registrations_chart'));
chart.draw(view, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="registrations_chart"></div>
EDIT
there are no standard options for annotation position
but you can move them manually, once the chart's 'ready' event fires
or in this case, the 'animationfinish' event
see following working snippet,
the total annotations are moved down...
google.charts.load('50', {
packages:['corechart']
}).then(function () {
var myHeight = 350;
var data = new google.visualization.DataTable();
data.addColumn('string', 'Registrations');
data.addColumn('number', 'Regular');
data.addColumn('number', 'Work Study');
data.addRows([
['Adult', 20, 12],
['Teen', 3, 0]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0,
1, {
calc: function (dt, row) {
return dt.getValue(row, 1);
},
type: "number",
role: "annotation"
},
2, {
calc: function (dt, row) {
return dt.getValue(row, 2);
},
type: "number",
role: "annotation"
},
{
calc: function (dt, row) {
return 0;
},
label: "Total",
type: "number",
},
{
calc: function (dt, row) {
return dt.getValue(row, 1) + dt.getValue(row, 2);
},
type: "number",
role: "annotation"
}
]);
var options = {
animation:{
duration: 1000,
easing: 'out',
startup: true
},
title: 'Registrations',
backgroundColor: 'transparent',
height: myHeight, width: 500,
legend: {
position: 'top',
maxLines: 3
},
bar: { groupWidth: '75%' },
isStacked: true,
series: {
2: {
annotations: {
stem: {
color: "transparent",
},
textStyle: {
color: "#000000",
}
},
enableInteractivity: false,
tooltip: "none",
visibleInLegend: false
}
}
};
var chart = new google.visualization.BarChart(document.getElementById('registrations_chart'));
google.visualization.events.addListener(chart, 'animationfinish', function () {
$('#registrations_chart text[fill="#000000"]').each(function (index, annotation) {
if (!isNaN(parseFloat(annotation.textContent))) {
var yCoord = parseFloat($(annotation).attr('y'));
$(annotation).attr('y', yCoord + 18);
}
});
});
chart.draw(view, options);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="registrations_chart"></div>

Displaying percentages in stacked bar Google Charts

// 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.
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.
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