[Chartjs]-How to modify chartjs tooltip so i can add customized strings in tooltips

11👍

Redefine default global tooltip template as follows:

Chart.defaults.global.tooltipTemplate =
  "<%if (label){%><%=label%>: <%}%><%= value %>";

Here is another example:

var ctx = document.getElementById("canvas").getContext("2d");

var myBarChart = new Chart(ctx).Bar(data, {
        tooltipTemplate: "<%= value %> Files"
});

4👍

The great previous answers do not work with chartjs 3. This example is from the official documentation:

const chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
    plugins: {
        tooltip: {
            callbacks: {
                label: function(context) {
                    const label = context.dataset.label || '';

                    if (label) {
                        label += ': ';
                    }
                    if (context.parsed.y !== null) {
                        label += new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(context.parsed.y);
                    }
                    return label;
                }}}}}});

1👍

Drawing from other responses I’ve found that helped me, apparently the label properties can be set to functions, For example, to format currency:

var overrides = {
  // show lables as currency
  scaleLabel: toCurrency,

  // String - Template string for single tooltips
  tooltipTemplate: toCurrency,

  // String - Template string for multiple tooltips
  multiTooltipTemplate: toCurrency
}

function toCurrency(label) {
    return '$' + label.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

Leave a comment