How get sum of total values in stackedBar ChartJs - chart.js

I'm trying to get the sum of all values of a stackedBar and include this total in tooltip.
Note: my datasets aren't static, this is an example
var barChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: 'Corporation 1',
backgroundColor: "rgba(220,220,220,0.5)",
data: [50, 40, 23, 45, 67, 78, 23]
}, {
label: 'Corporation 2',
backgroundColor: "rgba(151,187,205,0.5)",
data: [50, 40, 78, 23, 23, 45, 67]
}, {
label: 'Corporation 3',
backgroundColor: "rgba(151,187,205,0.5)",
data: [50, 67, 78, 23, 40, 23, 55]
}]
};
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
title:{
display:true,
text:"Chart.js Bar Chart - Stacked"
},
tooltips: {
mode: 'label',
callbacks: {
label: function(tooltipItem, data) {
var corporation = data.datasets[tooltipItem.datasetIndex].label;
var valor = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
var total = eval(data.datasets[tooltipItem.datasetIndex].data.join("+"));
return total+"--"+ corporation +": $" + valor.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
}
}
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true
}]
}
}
});
};
Now total is the sum per dataset and I need the sum per stackedBar.
Example
Label A: value A
Label B: value B
Label C: value C
TOTAL: value A + value B + value C
It is possible to get that total value?
Thanks, Idalia.

First you should know that if you return an array instead of a single string in the callback of the tooltip, it will display all the strings in your array as if it were different datasets (see this answer for more details).
So I edited a little bit your callback to the following:
callbacks: {
label: function(tooltipItem, data) {
var corporation = data.datasets[tooltipItem.datasetIndex].label;
var valor = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
// Loop through all datasets to get the actual total of the index
var total = 0;
for (var i = 0; i < data.datasets.length; i++)
total += data.datasets[i].data[tooltipItem.index];
// If it is not the last dataset, you display it as you usually do
if (tooltipItem.datasetIndex != data.datasets.length - 1) {
return corporation + " : $" + valor.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
} else { // .. else, you display the dataset and the total, using an array
return [corporation + " : $" + valor.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,'), "Total : $" + total];
}
}
}
You can see the full code in this jsFiddle, and here is its result :

i modified tektiv answer to show Total only for active sets and move it to tooltips footer.
tooltips: {
mode: 'label',
callbacks: {
afterTitle: function() {
window.total = 0;
},
label: function(tooltipItem, data) {
var corporation = data.datasets[tooltipItem.datasetIndex].label;
var valor = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
window.total += valor;
return corporation + ": " + valor.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
},
footer: function() {
return "TOTAL: " + window.total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
}
}
}

Shorter version of Gaspar's answer:
tooltips: {
callbacks: {
footer: (tooltipItems, data) => {
let total = tooltipItems.reduce((a, e) => a + parseInt(e.yLabel), 0);
return 'Total: ' + total;
}
}
}
Example: https://jsfiddle.net/g3ba60zc/2/

In the other answers you replace the last dataset, with this you don't need to
tooltips: {
callbacks: {
title: function(tooltipItems, data) {
return _this.chart.data.labels[tooltipItems[0].index];
},
footer: function(tooltipItems, data) {
let total = 0;
for (let i = 0; i < tooltipItems.length; i++) {
total += parseInt(tooltipItems[i].yLabel, 10);
}
return 'Total: ' + total;
}
}
}
Ps: It's typescript lang.

#Haider this is what you were looking for, I had the same problem.
I have reused your code and built upon it #tektiv
I have made one small change where instead of building into the label I have made use of the afterbody. This removes the key color
afterBody code:
afterBody: function (tooltipItem, data) {
var corporation = data.datasets[tooltipItem[0].datasetIndex].label;
var valor = data.datasets[tooltipItem[0].datasetIndex].data[tooltipItem[0].index];
var total = 0;
for (var i = 0; i < data.datasets.length; i++)
total += data.datasets[i].data[tooltipItem[0].index];
return "Total : $" + total;
}
Full code here at JSFiddle
Picture demonstration of the finished tooltip

Using Chart.js 2.5.0
var valor = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
returns a string value. To calculate the correct sum value you have to add a parseFloat statement:
tooltips: {
mode: 'label',
callbacks: {
afterTitle: function() {
window.total = 0;
},
label: function(tooltipItem, data) {
var corporation = data.datasets[tooltipItem.datasetIndex].label;
var valor = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
//THIS ONE:
valor=parseFloat(valor);
window.total += valor;
return corporation + ": " + valor.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
},
footer: function() {
return "TOTAL: " + window.total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
}
}
}

If you are on older ChartJs version you have to handle this in a different way. I'm using Chart.js Version 2.7.2 and this is how I handled it:
tooltips: {
mode: 'label',
callbacks: {
footer: function (data) {
var total = 0;
for (var i = 0; i < data.length; i++) {
total += data[i].yLabel;
}
return 'Total: ' + total
}
}
}

Chart.js made their own, very satisfying solution:
options: {
interaction: {
intersect: false,
mode: 'index',
},
plugins: {
tooltip: {
callbacks: {
footer: footer,
}
}
}
}
and somewhere else in your code:
const footer = (tooltipItems) => {
let sum = 0;
tooltipItems.forEach(function(tooltipItem) {
sum += tooltipItem.parsed.y;
});
return 'Sum: ' + sum;
};
Worked just fine for me!

Related

ChartJS multiple tooltip callbacks not working

I'm trying to calculate the sum of the dataset values at the end of a tooltip in ChartJS.
When I execute this code in "label" callback, works correctly. However, when I execute this code in a different callback in "afterBody" or "footer" callback, it results in NaN.
new Chart(document.getElementById("line-chart"), {
type: 'line',
data: {
labels: [2018, 2019, 2020],
datasets: [{
data: [1.09, 1.48, 2.48],
label: "ABC",
borderColor: "#3e95cd",
fill: false
}, {
data: [0.63, 0.81, 0.95],
label: "DEF",
borderColor: "#8e5ea2",
fill: false
}, {
data: [0.17, 0.17, 0.18],
label: "GHI",
borderColor: "#3cba9f",
fill: false
}]
},
options: {
title: {
display: true,
text: 'Past 2FY + Current FY Estimate, US$ millions'
},
tooltips: {
mode: 'index',
callbacks: {
label: function(tooltipItem, data) {
if (tooltipItem.index > 0) {
var previousdata = tooltipItem.index - 1;
var growth = ", YoY: " + ((data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index] / data.datasets[tooltipItem.datasetIndex].data[previousdata] * 100) - 100).toFixed(1) + "%";
} else {
var growth = '';
};
return data.datasets[tooltipItem.datasetIndex].label + ': $' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index] + growth;
},
afterBody: function(tooltipItem, data){
var total = 0;
for(var i=0; i < data.datasets.length; i++)
total += data.datasets[i].data[tooltipItem.index];
return 'Sum:'+total;
}
}
}
}
});
<canvas id="line-chart"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
Any help will be great!
I expect tooltip "Sum:" returns the sum of dataset values (in this case 'ABC' + 'CDE' + 'GHI' values).
Your use case is the given example for tooltip callbacks on the Chart.js samples page with the following code:
// Use the footer callback to display the sum of the items showing in the tooltip
footer: function(tooltipItems, data) {
var sum = 0;
tooltipItems.forEach(function(tooltipItem) {
sum += data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
});
return 'Sum: ' + sum;
}
Editing your snippet as per the above example seems to yield the result you want, although you probably want it formatted to match the rest of your tooltip:
new Chart(document.getElementById("line-chart"), {
type: 'line',
data: {
labels: [2018, 2019, 2020],
datasets: [{
data: [1.09, 1.48, 2.48],
label: "ABC",
borderColor: "#3e95cd",
fill: false
}, {
data: [0.63, 0.81, 0.95],
label: "DEF",
borderColor: "#8e5ea2",
fill: false
}, {
data: [0.17, 0.17, 0.18],
label: "GHI",
borderColor: "#3cba9f",
fill: false
}]
},
options: {
title: {
display: true,
text: 'Past 2FY + Current FY Estimate, US$ millions'
},
tooltips: {
mode: 'index',
callbacks: {
label: function(tooltipItem, data) {
if (tooltipItem.index > 0) {
var previousdata = tooltipItem.index - 1;
var growth = ", YoY: " + ((data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index] / data.datasets[tooltipItem.datasetIndex].data[previousdata] * 100) - 100).toFixed(1) + "%";
} else {
var growth = '';
};
return data.datasets[tooltipItem.datasetIndex].label + ': $' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index] + growth;
},
footer: function(tooltipItems, data) {
var sum = 0;
tooltipItems.forEach(function(tooltipItem) {
sum += data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
});
return 'Sum: ' + sum;
}
}
}
}
});
<canvas id="line-chart"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>

chart.js value is two but only one display tooltip

I have web monitoring data and I want to graph with chart js library in javascript.
Multiple data are at the same moment. However, 'tooltip' displays only one piece of data. Why is this?
Please help me :(
I (A) Login-swlee.zabbix.dev selected and time is 06/25 02:23:21
I (B) First page-swlee.zabbix.dev selected and time is 06/25 02:23:21
I (A) and (B) both selected but tooltip is only one.
```
var colors = ["#FEB500", "#5F8CFC", "#ADC803", "#F0605D"]
var list = data.list;
var list2 = data.list2;
var list3 = data.list3;
var datasets = [];
var labels = [];
for (i = 0; i < list3.length; i++) {
var date = new Date(list3[i].clock * 1000).getTime();
if (labels.indexOf(date) < 0) {
labels.push(date);
}
}
labels.sort();
var tbody = document.getElementById('webTable').children[1];
for (var i = 0; i < list.length; i++) {
var item = list[i];
var td_name = [];
for (var j = 0; j < list2.length; j++) {
var item2 = list2[j];
if (item.hosts[0].hostid == item2.hostid && item2.key_.indexOf('web.test.rspcode') > -1) {
var label = item2.name.replace('$1', item2.key_.substring(17, item2.key_.length - 1).split(',')[0]).replace('$2', item2.key_.substring(17, item2.key_.length - 1).split(',')[1]);
//line chart
var dataset = {
data: [],
label: label,
fill: false,
spanGaps: true,
borderColor: colors[i]
};
for (var k = 0; k < list3.length; k++) {
var item3 = list3[k];
if (item2.itemid == item3.itemid) {
var date = new Date(list3[k].clock * 1000).getTime();
dataset.data.push(null);
if (labels.indexOf(date) > -1) {
dataset.data[labels.indexOf(date)] = item3.value;
}
}
}
datasets.push(dataset);
}
}
}
var ctx = document.getElementById("webChart").getContext("2d");
var gData = {
labels: labels,
datasets: datasets
}
var lineChart = new Chart(ctx, {
type: 'line',
data: gData,
options: {
responsive: true,
scales: {
yAxes: [{
ticks: {
stepSize: 200,
suggestedMin: 0,
suggestedMax: 600
}
}],
xAxes: [{
type: 'time',
time: {
unit: 'minute',
round: 'minute',
displayFormats: {
minute: 'h:mm'
}
},
gridLines: {
display: false
}
}]
},
elements: {
line: {
tension: 0,
}
},
animation: false,
hover: {
animationDuration: 0,
},
responsiveAnimationDuration: 0,
legend: {
display: true,
labels: {
fontColor: '#fff'
}
},
tooltips: {
callbacks: {
title: function(tooltipItems, data) {
return new Date(tooltipItems[0].xLabel).format('MM/dd hh:mm:ss');
}
}
}
}
});
You need to set tooltip­'s mode to index
­­­­­­­­
...
tooltips: {
mode: 'index', //<-- set this
callbacks: {
title: function(tooltipItems, data) {
return new Date(tooltipItems[0].xLabel).format('MM/dd hh:mm:ss');
}
}
}
...

Chartjs v2 - format tooltip for multiple data sets (bar and line)

Reading up a lot on how to format the tooltip in ChartJS v2.x utilizing the tooltip callback. I've had success thus far, but find that I'm unable to define two separate formats for the two data sets I have.
As a bit more context, I have a line chart overlayed on top of a bar chart:
My bar data is numerical (in the millions, and needs to be rounded and truncated).
Example: 22345343 needs to be shown as 22M in the tooltip
My line data is a currency
Example: 146.36534 needs to shown as $146.37 in the tooptip
Here's my short WIP code thus far. This formats the tooltip to round and include the $ sign. How can I expand this so that I can separately format my bar data correctly in the tooltip?
tooltips: {
mode: 'index',
intersect: false,
callbacks: {
label: function(tooltipItem, data) {
return "$" + Number(tooltipItem.yLabel).toFixed(2).replace(/./g, function(c, i, a) {
return i > 0 && c !== "." && (a.length - i) % 3 === 0 ? "," + c : c;
});
}
}
}
You could achieve that using the following tooltips callback function ...
callbacks: {
label: function (t, d) {
if (t.datasetIndex === 0) {
return '$' + t.yLabel.toFixed(2)
} else if (t.datasetIndex === 1) {
return Math.round(+t.yLabel.toString().replace(/(\d{2})(.*)/, '$1.$2')) + 'M';
}
}
}
ᴅᴇᴍᴏ
var ctx = document.getElementById("canvas").getContext("2d");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["January", "February", "March", "April", "May"],
datasets: [{
type: 'line',
label: "Sales",
data: [144.36534, 146.42534, 145.23534, 147.19534, 145],
fill: false,
borderColor: '#EC932F',
backgroundColor: '#EC932F',
tension: 0,
yAxisID: 'y-axis-2'
}, {
type: 'bar',
label: "Visitor",
data: [22345343, 23345343, 24345343, 25345343, 230245343],
backgroundColor: '#71B37C',
yAxisID: 'y-axis-1'
}]
},
options: {
responsive: false,
tooltips: {
mode: 'index',
intersect: false,
callbacks: {
label: function (t, d) {
if (t.datasetIndex === 0) {
return '$' + t.yLabel.toFixed(2);
} else if (t.datasetIndex === 1) {
if (t.yLabel.toString().length === 9) {
return Math.round(+t.yLabel.toString().replace(/(\d{3})(.*)/, '$1.$2')) + 'M';
} else return Math.round(+t.yLabel.toString().replace(/(\d{2})(.*)/, '$1.$2')) + 'M';
}
}
}
},
scales: {
yAxes: [{
id: "y-axis-1",
position: "left"
}, {
id: "y-axis-2",
position: "right"
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="canvas" width="400" height="190"></canvas>
Try using below code!
let DoughnutForSavingCount = {
labels: [
intl.formatMessage({ id: 'Guarantee' }),
intl.formatMessage({ id: 'ILAS' }),
intl.formatMessage({ id: 'No Idea' })
],
datasets: [
/* Outer doughnut data starts*/
{
label: 'Graph1',
data: [
_.get(getClientSavingILASPolicyData[0], 'countwithGuaranttee') >
0 &&
_.get(getClientSavingILASPolicyData[0], 'totalWithGuarantee') ===
0
? 0.1
: _.get(getClientSavingILASPolicyData[0], 'totalWithGuarantee'),
_.get(getClientSavingILASPolicyData[0], 'countwithILAS', 0) > 0 &&
_.get(getClientSavingILASPolicyData[0], 'totalWithILAS') === 0
? 0.1
: _.get(getClientSavingILASPolicyData[0], 'totalWithILAS'),
_.get(getClientSavingILASPolicyData[0], 'countNoIdea', 0) > 0 &&
_.get(getClientSavingILASPolicyData[0], 'totalWithNoIdea') === 0
? 0.1
: _.get(getClientSavingILASPolicyData[0], 'totalWithNoIdea')
],
backgroundColor: ['#8c1aff', '#BF80FF', '#E9e9e9'],
hoverBackgroundColor: ['#8c1aff', '#BF80FF', '#E9e9e9']
},
/* Outer doughnut data ends*/
/* Inner doughnut data starts*/
{
label: 'Graph2',
data: [
_.get(getClientSavingILASPolicyData[0], 'countwithGuaranttee'),
_.get(getClientSavingILASPolicyData[0], 'countwithILAS'),
_.get(getClientSavingILASPolicyData[0], 'countNoIdea')
],
backgroundColor: ['#8c1aff', '#BF80FF', '#E9e9e9'],
hoverBackgroundColor: ['#8c1aff', '#BF80FF', '#E9e9e9']
}
/* Inner doughnut data ends*/
],
borderWidth: [1]
};
let DoughnutForSavingCountConfig = {
cutoutPercentage: 70,
legend: {
display: true,
position: 'bottom',
labels: {
fontColor: '#34A0DC',
fontSize: 10,
fontFamily: 'Helvetica',
boxWidth: 10,
usePointStyle: true
}
},
responsive: true,
plugins: {
datalabels: {
display: false
}
},
tooltips: {
enabled: true,
//*****add for reference********** */
callbacks: {
label: function(tooltipItems, data) {
if (tooltipItems.datasetIndex) {
var label = data.labels[tooltipItems.index] || '';
var currentValue =
data.datasets[tooltipItems.datasetIndex].data[
tooltipItems.index
];
if (label) {
label += ': ';
}
label += currentValue == '0.1' ? '0' : currentValue;
return label;
} else {
var label = data.labels[tooltipItems.index] || '';
var currentValue =
data.datasets[tooltipItems.datasetIndex].data[
tooltipItems.index
];
if (label) {
label += ': ';
}
label += intl.formatMessage({ id: 'HKD' }) + ' ';
label +=
currentValue == '0.1'
? '0'
: currentValue
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return label;
}
}
}
}
};
Thanks, GRUNT!
But since my datasets could me mixed it's better to use the yAxisID to check for the correct dataset.
tooltips: {
callbacks: {
label: function (tooltipItem, details) {
if (details.datasets[tooltipItem.datasetIndex].yAxisID == "$") {
let dataset = details.datasets[tooltipItem.datasetIndex];
let currentValue = dataset.data[tooltipItem.index];
return dataset.label + ": " + currentValue.toFixed(2) + " $";
} else {
let dataset = details.datasets[tooltipItem.datasetIndex];
let currentValue = dataset.data[tooltipItem.index];
return dataset.label + ": " + currentValue +" pieces";
}
}
}
}

Grid lines on google charts are not rendering as per data

Link to jsFiddle
google.charts.load('current', {
'packages': ['corechart']
});
//Input data
var data = [
['Data', 'CAT1', 'CAT2', 'CAT3', 'CAT4'],
['Provisions', 5, 0, 0, 0],
];
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
var options = {
colors: ['#00699B', '#087EB4', '#CBE7F7', '8A6996'],
isStacked: true,
chartArea: {
width: '40%'
},
bar: {
groupWidth: "40%"
},
// tooltip: { isHtml: true },
trigger: 'both',
vAxis: {
gridlines: {
color: '#0000006b',
minValue: 0,
baseline: 0
},
format: "$ #,###"
},
};
var dataTable = google.visualization.arrayToDataTable(data);
//Formatters
var intergerFormatter = new google.visualization.NumberFormat({
groupingSymbol: ",",
fractionDigits: 0
});
for (var i = 0; i < data[0].length; i++) {
intergerFormatter.format(dataTable, i);
}
var view = new google.visualization.DataView(dataTable);
var cols =   [0];
for (var i = 1; i < data[0].length; i++) {
cols.push({
sourceColumn: i,
type: "number",
label: data[0][i]
});
cols.push({
calc: createTooltip(i),
type: "string",
role: "tooltip",
});
}
view.setColumns(cols);
var chart = new google.visualization.ColumnChart(document.getElementById('provision_chart'));
chart.draw(view, options);
function createTooltip(col) {
return function(dataTable, row) {
var html = dataTable.getColumnLabel(col) + ":" + "\n";
html += "4 " + dataTable.getValue(row, 0) + "\n";
html += "$ " + intergerFormatter.formatValue(dataTable.getValue(row, col)) + " total" + "\n";
return html;
};
}
}
The grid lines on a stacked bar type google charts are not rendering properly.
As per the data, $5 is recorded against Category1, but when it's rendered the bar is slightly over $5.
Can someone suggest a fix?
removing the option --> format: "$ #,###" -- reveals the problem
although the tick mark displays --> $ 5 -- the actual number used is 4.5
see following working snippet...
google.charts.load('current', {
'packages': ['corechart']
});
//Input data
var data = [
['Data', 'CAT1', 'CAT2', 'CAT3', 'CAT4'],
['Provisions', 5, 0, 0, 0],
];
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
var options = {
colors: ['#00699B', '#087EB4', '#CBE7F7', '8A6996'],
isStacked: true,
chartArea: {
width: '40%'
},
bar: {
groupWidth: "40%"
},
// tooltip: { isHtml: true },
trigger: 'both',
vAxis: {
gridlines: {
color: '#0000006b',
minValue: 0,
baseline: 0
},
//format: "$ #,###"
},
};
var dataTable = google.visualization.arrayToDataTable(data);
//Formatters
var intergerFormatter = new google.visualization.NumberFormat({
groupingSymbol: ",",
fractionDigits: 0
});
for (var i = 0; i < data[0].length; i++) {
intergerFormatter.format(dataTable, i);
}
var view = new google.visualization.DataView(dataTable);
var cols =   [0];
for (var i = 1; i < data[0].length; i++) {
cols.push({
sourceColumn: i,
type: "number",
label: data[0][i]
});
cols.push({
calc: createTooltip(i),
type: "string",
role: "tooltip",
});
}
view.setColumns(cols);
var chart = new google.visualization.ColumnChart(document.getElementById('provision_chart'));
chart.draw(view, options);
function createTooltip(col) {
return function(dataTable, row) {
var html = dataTable.getColumnLabel(col) + ":" + "\n";
html += "4 " + dataTable.getValue(row, 0) + "\n";
html += "$ " + intergerFormatter.formatValue(dataTable.getValue(row, col)) + " total" + "\n";
return html;
};
}
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="provision_chart" style="width: 500px; height: 500px;"></div>
to correct, you can add a decimal place to the format --> $ #,##0.0
or provide your own vAxis.ticks in an array --> [0, 1, 2, 3, 4, 5, 6]
see following working snippet...
google.charts.load('current', {
'packages': ['corechart']
});
//Input data
var data = [
['Data', 'CAT1', 'CAT2', 'CAT3', 'CAT4'],
['Provisions', 5, 0, 0, 0],
];
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
var options = {
colors: ['#00699B', '#087EB4', '#CBE7F7', '8A6996'],
isStacked: true,
chartArea: {
width: '40%'
},
bar: {
groupWidth: "40%"
},
// tooltip: { isHtml: true },
trigger: 'both',
vAxis: {
gridlines: {
color: '#0000006b',
minValue: 0,
baseline: 0
},
format: "$ #,###",
ticks: [0, 1, 2, 3, 4, 5, 6]
},
};
var dataTable = google.visualization.arrayToDataTable(data);
//Formatters
var intergerFormatter = new google.visualization.NumberFormat({
groupingSymbol: ",",
fractionDigits: 0
});
for (var i = 0; i < data[0].length; i++) {
intergerFormatter.format(dataTable, i);
}
var view = new google.visualization.DataView(dataTable);
var cols =   [0];
for (var i = 1; i < data[0].length; i++) {
cols.push({
sourceColumn: i,
type: "number",
label: data[0][i]
});
cols.push({
calc: createTooltip(i),
type: "string",
role: "tooltip",
});
}
view.setColumns(cols);
var chart = new google.visualization.ColumnChart(document.getElementById('provision_chart'));
chart.draw(view, options);
function createTooltip(col) {
return function(dataTable, row) {
var html = dataTable.getColumnLabel(col) + ":" + "\n";
html += "4 " + dataTable.getValue(row, 0) + "\n";
html += "$ " + intergerFormatter.formatValue(dataTable.getValue(row, col)) + " total" + "\n";
return html;
};
}
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="provision_chart" style="width: 500px; height: 500px;"></div>
the getColumnRange(colIndex) method can assist in building the ticks dynamically
the method returns an object {} with properties for min and max for the column index provided
see following working snippet for an example...
google.charts.load('current', {
'packages': ['corechart']
});
//Input data
var data = [
['Data', 'CAT1', 'CAT2', 'CAT3', 'CAT4'],
['Provisions', 5, 0, 0, 0],
];
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
var options = {
colors: ['#00699B', '#087EB4', '#CBE7F7', '8A6996'],
isStacked: true,
chartArea: {
width: '40%'
},
bar: {
groupWidth: "40%"
},
// tooltip: { isHtml: true },
trigger: 'both',
vAxis: {
gridlines: {
color: '#0000006b',
minValue: 0,
baseline: 0
},
format: "$ #,###"
},
};
var dataTable = google.visualization.arrayToDataTable(data);
//Formatters
var intergerFormatter = new google.visualization.NumberFormat({
groupingSymbol: ",",
fractionDigits: 0
});
for (var i = 0; i < data[0].length; i++) {
intergerFormatter.format(dataTable, i);
}
var view = new google.visualization.DataView(dataTable);
var cols = [0];
var ticksY = [];
var maxY = null;
var minY = null;
for (var i = 1; i < view.getNumberOfColumns(); i++) {
var range = view.getColumnRange(i);
if (maxY === null) {
maxY = Math.ceil(range.max);
} else {
maxY = Math.max(maxY, Math.ceil(range.max));
}
if (minY === null) {
minY = Math.floor(range.min);
} else {
minY = Math.min(minY, Math.floor(range.min));
}
}
for (var i = minY; i <= maxY + 1; i++) {
ticksY.push(i);
}
options.vAxis.ticks = ticksY;
for (var i = 1; i < data[0].length; i++) {
cols.push({
sourceColumn: i,
type: "number",
label: data[0][i]
});
cols.push({
calc: createTooltip(i),
type: "string",
role: "tooltip",
});
}
view.setColumns(cols);
var chart = new google.visualization.ColumnChart(document.getElementById('provision_chart'));
chart.draw(view, options);
function createTooltip(col) {
return function(dataTable, row) {
var html = dataTable.getColumnLabel(col) + ":" + "\n";
html += "4 " + dataTable.getValue(row, 0) + "\n";
html += "$ " + intergerFormatter.formatValue(dataTable.getValue(row, col)) + " total" + "\n";
return html;
};
}
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="provision_chart" style="width: 500px; height: 500px;"></div>

Chart.js V2: Add prefix or suffix to tooltip label

In Chart.js V1.0, I would add tooltipTemplate: "<%if (label){%><%=label %>: <%}%><%= '€' + value %>" to add a euro symbol as prefix to the tooltip label. However, this no longer works in V2. Does anybody know the new way to do accomplish this? I can't seem to find it.
Many thanks!
In the V2.0 the tooltipTemplate option is deprecated. Instead you can use callbacks to modify the displayed tooltips. There is a sample for the usage of callbacks here and you can find the possible callbacks in the documentation under Chart.defaults.global.tooltips
In your case I would do the following:
window.myLine = new Chart(chart, {
type: 'line',
data: lineChartData,
options: {
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
label: function(tooltipItems, data) {
return tooltipItems.yLabel + ' €';
}
}
},
}
});
Don't forget to set the HTML meta tag:
<meta charset="UTF-8">
In addition to iecs' answer, if you want to return the exact default text and add some more (like a € sign in your case), use following syntax :
var ctx = $(chartCanvas);
window.chartObject = new Chart(ctx, {
type: 'bar',
data: chartData,
options: {
tooltips: {
callbacks: {
label: function(tooltipItems, data) {
return data.datasets[tooltipItems.datasetIndex].label +': ' + tooltipItems.yLabel + ' €';
}
}
}
}
});
See if it helps:
var config = {
options: {
tooltips: {
callbacks: {
title: function (tooltipItem, data) { return data.labels[tooltipItem[0].index]; },
label: function (tooltipItem, data) {
var amount = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
var total = eval(data.datasets[tooltipItem.datasetIndex].data.join("+"));
return amount + ' / ' + total + ' ( ' + parseFloat(amount * 100 / total).toFixed(2) + '% )';
},
//footer: function(tooltipItem, data) { return 'Total: 100 planos.'; }
}
},
}
};
This set "label + value + €"
options: {
legend: {
display: false
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
return data.labels[tooltipItem.index] + ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index] + '€';
}
}
}
}
If you have a stacked bar chart (and I assume a stacked line chart) and you want to format all the data points included in a single bar with a currency symbol, you can do something like this:
tooltips: {
mode: 'label',
callbacks: {
label: function (tooltipItems, data) {
return '$' + tooltipItems.yLabel;
}
}
},
Note the value of mode.
If you want to have finer control of the tool tip, for example include the labels as they appear the chart's legend, you can do something like this:
tooltips: {
mode: 'single', // this is the Chart.js default, no need to set
callbacks: {
label: function (tooltipItems, data) {
var i, label = [], l = data.datasets.length;
for (i = 0; i < l; i += 1) {
label[i] = data.datasets[i].label + ' : ' + '$' + data.datasets[i].data[tooltipItems.index];
}
return label;
}
}
},
Just updating #Luc Lérot's answer.
I had the same problem and his code helped me out but not fixed it, I had to modify it to work for me.
Using Chart.js version 2.6.0
var ctx = $(chartCanvas);
window.chartObject = new Chart(ctx, {
type: 'bar',
data: chartData,
options: {
tooltips: {
callbacks: {
label: function (tooltipItems, data) {
return data.datasets[tooltipItems.datasetIndex].label + ': ' + data.datasets[tooltipItems.datasetIndex].data[tooltipItems.index] + ' €';
}
}
}
}
});
To generalize code, let's use unitPrefix and unitSuffix for the datasets, for example:
datasets: [
{
label: 'Loss Rate',
data: [],
unitSuffix: "%",
},
{
label: 'Price',
data: [],
unitPrefix: "$",
},
Then we could have this code:
options: {
tooltips: {
callbacks: {
label: function (tooltipItem, data) {
let dataset = data.datasets[tooltipItem.datasetIndex];
let blocks = [];
if (dataset.label) {
blocks.push(${dataset.label} + ':');
}
if (dataset.unitPrefix) {
blocks.push(dataset.unitPrefix);
}
blocks.push(dataset.data[tooltipItem.index])
if (dataset.unitSuffix) {
blocks.push(dataset.unitSuffix);
}
return blocks.join(' ');
},
},
},
},
As we continue our way along the release chain, the answer once again changes in Chart.js v3.X with the updated options API.
An example of adding temperature units is as follows:
const options = {
plugins: {
tooltip: {
callbacks: {
label: (item) =>
`${item.dataset.label}: ${item.formattedValue} °C`,
},
},
},
}
Chart.js version 3.9.1
const options: ChartOptions = {
plugins: {
tooltip: {
callbacks: {
label: ({ label, formattedValue }) => `${label}:${formattedValue}g`
}
}
}
}