Google charts show unformatted value in tooltip - charts

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>

Related

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>

Google Visualization Chart horizontal bar with target (vertical line

I would like to set up a small and light chart using Google Visualizion chart.
The idea would be to have an horizontal bar chart (this I know how to do) BUT combined with a vertical line showing if a target is exceeded or not.
The target can be different for each data.
In addition I would like to include an indicator (red/green) easily identifying who is under target and who is above (+ optinally a label just after the green/red dot).
Any idea how to proceed?
actually, you can just use a BarChart,
and change the series type for the last two columns...
series: {
1: {
type: 'line'
},
2: {
type: 'scatter'
}
}
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({type: 'string', id: 'x'});
dataTable.addColumn({type: 'number', id: 'bar'});
dataTable.addColumn({type: 'string', role: 'annotation'});
dataTable.addColumn({type: 'number', id: 'line'});
dataTable.addColumn({type: 'number', id: 'scatter'});
dataTable.addColumn({type: 'string', role: 'style'});
dataTable.addRows([
['', 300, '300', 300, 800, '#4caf50'],
['', 600, '600', 600, 800, '#f44336'],
['', 200, '200', 200, 800, '#4caf50'],
['', 150, '150', 150, 800, '#f44336'],
]);
var options = {
annotations: {
alwaysOutside: true,
textStyle: {
color: '#000000'
}
},
colors: ['#9e9e9e', '#2196f3'],
legend: 'none',
hAxis: {
gridlines: {
count: 0
},
textPosition: 'none'
},
series: {
1: {
lineWidth: 4,
type: 'line'
},
2: {
type: 'scatter'
}
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart'));
chart.draw(dataTable, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>
EDIT
to add custom labels next to the scatter points,
you can use chart method --> getChartLayoutInterface()
which has a method for --> getBoundingBox(id)
this can be used to find the position of a chart element.
where id is the string id of the point, in this format --> point#series#row -- point#0#0
on the chart's 'ready' event, we can position custom labels next to the points.
google.visualization.events.addListener(chart, 'ready', function (sender) {
var padding = 16;
var chartLayout = chart.getChartLayoutInterface();
var containerBounds = chart.getContainer().getBoundingClientRect();
for (var row = 0; row < dataTable.getNumberOfRows(); row++) {
var pointBounds = chartLayout.getBoundingBox('point#2#' + row);
var dataLabel = document.createElement('span');
dataLabel.className = 'data-label';
dataLabel.innerHTML = 'Label ' + row;
dataLabel.style.top = (containerBounds.top + pointBounds.top - (pointBounds.height / 2)) + 'px';
dataLabel.style.left = (containerBounds.left + pointBounds.left + pointBounds.width + padding) + 'px';
chart.getContainer().appendChild(dataLabel);
}
});
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({type: 'string', id: 'x'});
dataTable.addColumn({type: 'number', id: 'bar'});
dataTable.addColumn({type: 'string', role: 'annotation'});
dataTable.addColumn({type: 'number', id: 'line'});
dataTable.addColumn({type: 'number', id: 'scatter'});
dataTable.addColumn({type: 'string', role: 'style'});
dataTable.addRows([
['', 300, '300', 300, 800, '#4caf50'],
['', 600, '600', 600, 800, '#f44336'],
['', 200, '200', 200, 800, '#4caf50'],
['', 150, '150', 150, 800, '#f44336'],
]);
var options = {
annotations: {
alwaysOutside: true,
textStyle: {
color: '#000000'
}
},
colors: ['#9e9e9e', '#2196f3'],
legend: 'none',
hAxis: {
gridlines: {
count: 0
},
textPosition: 'none'
},
series: {
1: {
lineWidth: 4,
type: 'line'
},
2: {
type: 'scatter'
}
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart'));
google.visualization.events.addListener(chart, 'ready', function (sender) {
var padding = 16;
var chartLayout = chart.getChartLayoutInterface();
var containerBounds = chart.getContainer().getBoundingClientRect();
for (var row = 0; row < dataTable.getNumberOfRows(); row++) {
var pointBounds = chartLayout.getBoundingBox('point#2#' + row);
var dataLabel = document.createElement('span');
dataLabel.className = 'data-label';
dataLabel.innerHTML = 'Label ' + row;
dataLabel.style.top = (containerBounds.top + pointBounds.top - (pointBounds.height / 2)) + 'px';
dataLabel.style.left = (containerBounds.left + pointBounds.left + pointBounds.width + padding) + 'px';
chart.getContainer().appendChild(dataLabel);
}
});
chart.draw(dataTable, options);
});
.data-label {
position: absolute;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>

How to add annotation to Google Bar Chart where dataset comes from Google Sheet [duplicate]

I need to put labels over my google.chart.Bar (not google.visualization.BarChart) the chart is correctly visualized but only shows values on mouse over the bars,please helpme!.
without mouse over
with mouse over
the data is taked from hidden inputs... here the code :
var data3 = new google.visualization.arrayToDataTable([
['Ambitos', 'Programados', 'Terminados',{ role: 'style' }],
['ex', parseInt(document.getElementById("sumex").value),(parseInt(document.getElementById("sumex").value))-( parseInt(document.getElementById("sumpex").value)),document.getElementById("sumex").value],
['ma', parseInt(document.getElementById("summa").value),(parseInt(document.getElementById("summa").value))-( parseInt(document.getElementById("sumpma").value)),document.getElementById("summa").value],
['mo', parseInt(document.getElementById("summo").value),(parseInt(document.getElementById("summo").value))-( parseInt(document.getElementById("sumpmo").value)),document.getElementById("summo").value],
['re', parseInt(document.getElementById("sumre").value),(parseInt(document.getElementById("sumre").value))-( parseInt(document.getElementById("sumpre").value)),document.getElementById("sumre").value],
['tx', parseInt(document.getElementById("sumtx").value),(parseInt(document.getElementById("sumtx").value))-( parseInt(document.getElementById("sumptx").value)),document.getElementById("sumtx").value]]);
var view3 = new google.visualization.DataView(data3);
view3.setColumns([0,1,2,
{ calc: "stringify",
sourceColumn: 3,
type: "string",
role: "annotation" },3]);
var options3 = {
legend: { position: "none" },
chart: {
title: 'Resumen General',
subtitle: 'programados v/s terminados'},
series: {},
axes: { y: {
distance: {label: ''}, } },
chartArea : { width:"95%", height:"80%"} };
var chart3 = new google.charts.Bar(document.getElementById('barras'));
chart3.draw(data3, options3);
p.d. sorry for my bad english!
unfortunately, annotations (bar labels) are not supported on Material charts
recommend using Core chart, with the following option instead...
theme: 'material'
an separate annotation column should be added for each series column,
that should have annotations
when using a DataView to add annotation columns,
be sure to draw the chart using the view (view3),
instead of the original data table (data3)
see following working snippet...
google.charts.load('current', {
callback: function () {
var data3 = new google.visualization.arrayToDataTable([
['Ambitos', 'Programados', 'Terminados',{ role: 'style' }],
['ex', 8,(8)-(6),''],
['ma', 6,(6)-(4),''],
['mo', 4,(4)-(2),''],
['re', 2,(2)-(1),''],
['tx', 1,(1)-(0),'']]);
var view3 = new google.visualization.DataView(data3);
view3.setColumns([0,
1,
{
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
},
2,
{
calc: "stringify",
sourceColumn: 2,
type: "string",
role: "annotation"
},
3
]);
var options3 = {
legend: { position: "none" },
chart: {
title: 'Resumen General',
subtitle: 'programados v/s terminados'
},
series: {},
axes: {
y: {
distance: {label: ''},
}
},
chartArea : {
width:"95%",
height:"80%"
},
theme: 'material'
};
var chart3 = new google.visualization.ColumnChart(document.getElementById('barras'));
chart3.draw(view3, options3);
},
packages:['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="barras"></div>
note: list of options unavailable to Material --> Tracking Issue for Material Chart Feature Parity

Tooltip number formatting in google chart

How can I format number in a tooltip in google chart? I tried to apply "none" formatting in datatable and also applied "####" formatting on h-axis in google chart option but still can see 2,012 in tooltip.
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
[
{label: "year", type: "number", format: "none"},
{label: "performance", type: "number", format: "none"},
],
["2009", 10],
["2010", 15],
["2011", 3],
["2012", 5]
]);
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: '#333'}, format: "####"},
vAxis: {minValue: 0}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
JSFiddle can be found here:
https://jsfiddle.net/ux37j0dk/3/
by default, the tooltip will display the formatted value of data table cell
you can use the NumberFormat class to format the data table...
var yearPattern = "0";
var formatNumber = new google.visualization.NumberFormat({
pattern: yearPattern
});
formatNumber.format(data, 0);
see following working snippet...
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
[{
label: "year",
type: "number",
format: "none"
},
{
label: "performance",
type: "number",
format: "none"
},
],
["2009", 10],
["2010", 15],
["2011", 3],
["2012", 5]
]);
var yearPattern = "0";
var formatNumber = new google.visualization.NumberFormat({
pattern: yearPattern
});
formatNumber.format(data, 0);
var options = {
title: 'Company Performance',
hAxis: {
title: 'Year',
titleTextStyle: {
color: '#333'
},
format: yearPattern
},
vAxis: {
minValue: 0
}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
you can also use object notation to supply both the value (v:) and the formatted value (f:),
when loading the data table...
[{v: "2009", f: "2009"}, 10],
see following working snippet...
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
[{
label: "year",
type: "number",
format: "none"
},
{
label: "performance",
type: "number",
format: "none"
},
],
[{v: "2009", f: "2009"}, 10],
[{v: "2010", f: "2010"}, 15],
[{v: "2011", f: "2011"}, 3],
[{v: "2012", f: "2012"}, 5]
]);
var yearPattern = "0";
var options = {
title: 'Company Performance',
hAxis: {
title: 'Year',
titleTextStyle: {
color: '#333'
},
format: yearPattern
},
vAxis: {
minValue: 0
}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

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>