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

10

55

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!

Dorser answered 11/1, 2016 at 11:35 Comment(1)
Here is an example an Doughnut chart with a percentage tooltip (Chart.js 4.4.0) linkLuxor
P
126

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">
Paff answered 18/1, 2016 at 12:47 Comment(3)
If you have problems displaying the tooltips after that, please look into this issue and how to fix it: github.com/nnnick/Chart.js/issues/1891Paff
for v3, I resolved the issue by options: { plugins: { tooltip: { callbacks: { label: callbackFunction } } } }Biron
v3 official example here chartjs.org/docs/3.5.0/configuration/tooltip.htmlBuchalter
O
60

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 + ' €';
                }
            }

        }
    }
});
Omen answered 31/5, 2016 at 18:9 Comment(2)
This is what I've been searching for half the day, thank you!! All other suggestions kept replacing the default text and label.Solberg
V3 has an example of how to do this chartjs.org/docs/3.5.0/configuration/tooltip.htmlBuchalter
D
21

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.'; }
                    }
                },
            }
        };
Demythologize answered 15/6, 2016 at 18:7 Comment(1)
Using ChartJS 2.7.1 and the above helped me to display the Label, Value and a Symbol after many hours of searching.Impoverish
S
13

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] + '€';
            }
        }
    }
}
Separative answered 23/7, 2018 at 18:31 Comment(2)
This is the only thing that worked for me. The accepted answer doesn't work for me, maybe it did work at the time...Sachasachem
This answer works for Donut, Pie and other type of graphs like this. This should be the accepted answer I guess.Crossfertilization
M
8

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;
            }
        }
    },
Mossbunker answered 6/11, 2016 at 10:22 Comment(1)
This worked for me with a slight modification on the first code block. There's an extra 's in tooltipItem in this line return '$' + tooltipItems.yLabel. This results in no tool tips visible.Noami
J
7

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] + ' €';
                   }
              }

        }
    }
});
Jethro answered 6/10, 2017 at 17:49 Comment(0)
I
3

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`,
            },
        },
    },
}
Indefinite answered 21/4, 2022 at 9:5 Comment(0)
S
1

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(' ');
            },
        },
    },
},
Siberson answered 17/12, 2020 at 16:36 Comment(0)
C
0

Chart.js version 3.9.1

const options: ChartOptions = {
  plugins: {
    tooltip: {
      callbacks: {
        label: ({ label, formattedValue }) => `${label}:${formattedValue}g`
      }
    }
  }
}
Conchiolin answered 1/9, 2022 at 1:46 Comment(0)
A
0

See tooltip section:

const options = {
      interaction: {
        mode: "nearest",
        intersect: false,
      },
      scales: {
        y: {
          grid: {
            display: false,
          },
          position: "right",
        },
        x: {
          ticks: {
            maxRotation: 0,
            minRotation: 0,
          },
        },
      },
      plugins: {
        legend: {
          display: false,
        },
        tooltip: {
          callbacks: {
            title: function (context) {
              return data[context[0].dataIndex].date //in title you have to call context[0] in order to get current item
            },
            label: function (context) {
              return context.raw //raw will give you the label value
            },

            intersect: false,
            backgroundColor: "#51d198",
          },
        },
      },
    }
Appease answered 4/1 at 22:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.