[javascript] JavaScript Chart.js - Custom data formatting to display on tooltip

I have looked at various documentation and similar questions on here, but cannot seem to find the particular solution. Apologies if I have missed anything obvious or have repeated this question!

As a bit of background info, I have implemented 4 graphs using the Chart.js plugin and passed in the required data using PHP from a database. This is all working correctly and is fine.

My problem is I need to display the data in the tooltips as formatted data aka. as numeric with %. As an example, one of my data from database is -0.17222. I have formatted it as a percentage to display in my table and all is well. However, when setting the data for the chart.js bar graph, the data is obviously missing this formatting and displaying as the -0.17222 which I do not want.

Sorry, I wanted to post a picture, but my reputation is too rubbish!

I grab data from database, then set into my table:

var kpiRex = new Handsontable(example1, {
    data: getRexData(),

Then I feed this data like so in the chart section:

data: kpiRex.getDataAtRow(3)

Any help would be great! I've been stuck on this for hours and it's probably something really simple I am overlooking.

The answer is


You need to make use of Label Callback. A common example to round data values, the following example rounds the data to two decimal places.

var chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        tooltips: {
            callbacks: {
                label: function(tooltipItem, data) {
                    var label = data.datasets[tooltipItem.datasetIndex].label || '';

                    if (label) {
                        label += ': ';
                    }
                    label += Math.round(tooltipItem.yLabel * 100) / 100;
                    return label;
                }
            }
        }
    }
});

Now let me write the scenario where I used the label callback functionality.

Let's start with logging the arguments of Label Callback function, you will see structure similar to this here datasets, array comprises of different lines you want to plot in the chart. In my case it's 4, that's why length of datasets array is 4.

enter image description here

In my case, I had to perform some calculations on each dataset and have to identify the correct line, every-time I hover upon a line in a chart.

To differentiate different lines and manipulate the data of hovered tooltip based on the data of other lines I had to write this logic.

  callbacks: {
    label: function (tooltipItem, data) {
      console.log('data', data);
      console.log('tooltipItem', tooltipItem);
      let updatedToolTip: number;
      if (tooltipItem.datasetIndex == 0) {
        updatedToolTip = tooltipItem.yLabel;
      }
      if (tooltipItem.datasetIndex == 1) {
        updatedToolTip = tooltipItem.yLabel - data.datasets[0].data[tooltipItem.index];
      }
      if (tooltipItem.datasetIndex == 2) {
        updatedToolTip = tooltipItem.yLabel - data.datasets[1].data[tooltipItem.index];
      }
      if (tooltipItem.datasetIndex == 3) {
        updatedToolTip = tooltipItem.yLabel - data.datasets[2].data[tooltipItem.index]
      }
      return updatedToolTip;
    }
  } 

Above mentioned scenario will come handy, when you have to plot different lines in line-chart and manipulate tooltip of the hovered point of a line, based on the data of other point belonging to different line in the chart at the same index.


This is what my final options section looks like for chart.js version 2.8.0.

        options: {
        legend: {
            display: false //Have this or else legend will display as undefined
        },
        scales: {
            //This will show money for y-axis labels with format of $xx.xx
            yAxes: [{
              ticks: {
                beginAtZero: true,
                callback: function(value) {
                    return (new Intl.NumberFormat('en-US', {
                        style: 'currency',
                        currency: 'USD',
                    })).format(value);
                }
              }
            }]
        },
        //This will show money in tooltip with format of $xx.xx
        tooltips: {
            callbacks: {
                label: function (tooltipItem) {
                    return (new Intl.NumberFormat('en-US', {
                        style: 'currency',
                        currency: 'USD',
                    })).format(tooltipItem.value);
                }
            }
        }
    }

I wanted to show money values for both the y-axis and the tooltip values that show up when you hover over them. This works to show $49.99 and values with zero cents (ex: $50.00)


This works perfectly fine with me. It takes label and format the value.

options: {
        tooltips: {
            callbacks: {
                label: function(tooltipItem, data) {

                    let label = data.labels[tooltipItem.index];
                    let value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
                    return ' ' + label + ': ' + value + ' %';

                }
            }
        }
    }

tooltips: {
          callbacks: {
            label: (tooltipItem, data) => {
              // data for manipulation
              return data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
            },
          },
        },

For chart.js 2.0+, this has changed (no more tooltipTemplate/multiTooltipTemplate). For those that just want to access the current, unformatted value and start tweaking it, the default tooltip is the same as:

options: {
    tooltips: {
        callbacks: {
            label: function(tooltipItem, data) {
                return tooltipItem.yLabel;
            }
        }
    }
}

I.e., you can return modifications to tooltipItem.yLabel, which holds the y-axis value. In my case, I wanted to add a dollar sign, rounding, and thousands commas for a financial chart, so I used:

options: {
    tooltips: {
        callbacks: {
            label: function(tooltipItem, data) {
                return "$" + Number(tooltipItem.yLabel).toFixed(0).replace(/./g, function(c, i, a) {
                    return i > 0 && c !== "." && (a.length - i) % 3 === 0 ? "," + c : c;
                });
            }
        }
    }
}

tooltips: {
    callbacks: {
        label: function (tooltipItem) {
            return (new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: 'USD',
            })).format(tooltipItem.value);
        }
    }
}

tooltips: {
            enabled: true,
                  mode: 'single',
                  callbacks: {
                    label: function(tooltipItems, data) { 
                      return data.datasets[tooltipItems.datasetIndex].label+": "+tooltipItems.yLabel;
                    }
                  }
                }

In Chart.Js 2.8.0, the configuration for custom tooltips can be found here: https://www.chartjs.org/docs/latest/configuration/tooltip.html#label-callback (Thanks to @prokaktus)

If you want to e.g. show some values with a prefix or postfix (In the example, the script adds a unit of kWh to the values in the chart), you could do this like:

options: {
  rotation: 1 * Math.PI,
  circumference: 1 * Math.PI,
  tooltips: {
    callbacks: {
      label: function(tooltipItem, data) {
        console.log(data);
        console.log(tooltipItem);

        var label = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index] || '';

        if (label) {
          label += ' kWh';
        }

        return label;
      }
    }
  }
}

An example fiddle is here, too: https://jsfiddle.net/y3petw58/1/


In chart.js 2.1.6, I did something like this (in typescript):

  let that = this;
  options = {
    legend: {
      display: false,
      responsive: false
    },
    tooltips: {
      callbacks: {
        label: function(tooltipItem, data) {
          let account: Account = that.accounts[tooltipItem.index];
          return account.accountNumber+":"+account.balance+"€";
        }
      }
    }
  }

You can give tooltipTemplate a function, and format the tooltip as you wish:

tooltipTemplate: function(v) {return someFunction(v.value);}
multiTooltipTemplate: function(v) {return someOtherFunction(v.value);}

Those given 'v' arguments contain lots of information besides the 'value' property. You can put a 'debugger' inside that function and inspect those yourself.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to string-formatting

JavaScript Chart.js - Custom data formatting to display on tooltip Format in kotlin string templates Converting Float to Dollars and Cents Chart.js - Formatting Y axis String.Format not work in TypeScript Use StringFormat to add a string to a WPF XAML binding How to format number of decimal places in wpf using style/template? How to left align a fixed width string? Convert Java Date to UTC String Format a Go string without printing?

Examples related to number-formatting

JavaScript Chart.js - Custom data formatting to display on tooltip Format / Suppress Scientific Notation from Python Pandas Aggregation Results Formula to convert date to number tSQL - Conversion from varchar to numeric works for all but integer Convert string to decimal number with 2 decimal places in Java What is ToString("N0") format? format a number with commas and decimals in C# (asp.net MVC3) SSRS custom number format Format telephone and credit card numbers in AngularJS How to format a number 0..9 to display with 2 digits (it's NOT a date)

Examples related to code-formatting

How do you format code on save in VS Code How do you format code in Visual Studio Code (VSCode) JavaScript Chart.js - Custom data formatting to display on tooltip Is there a command for formatting HTML in the Atom editor? How to auto-indent code in the Atom editor? Code formatting shortcuts in Android Studio for Operation Systems How to auto-format code in Eclipse? How to format code in Xcode? What is the proper way to format a multi-line dict in Python? How do I format XML in Notepad++?

Examples related to chart.js

Set height of chart in Chart.js how to set start value as "0" in chartjs? Setting width and height Chart.js v2 hide dataset labels How to format x-axis time scale values in Chart.js v2 How to set ChartJS Y axis title? how to display data values on Chart.js How to set max and min value for Y axis JavaScript Chart.js - Custom data formatting to display on tooltip In Chart.js set chart title, name of x axis and y axis?