Tooltip

Tooltip Configuration

Namespace: options.plugins.tooltip, the global options for the chart tooltips is defined in Chart.defaults.plugins.tooltip.

NameTypeDefaultDescription
enabledbooleantrueAre on-canvas tooltips enabled?
externalfunctionnullSee external tooltip section.
modestringinteraction.modeSets which elements appear in the tooltip. more….
intersectbooleaninteraction.intersectIf true, the tooltip mode applies only when the mouse position intersects with an element. If false, the mode will be applied at all times.
positionstring‘average’The mode for positioning the tooltip. more…
callbacksobjectSee the callbacks section.
itemSortfunctionSort tooltip items. more…
filterfunctionFilter tooltip items. more…
backgroundColorColor‘rgba(0, 0, 0, 0.8)’Background color of the tooltip.
titleColorColor‘#fff’Color of title text.
titleFontFont{style: ‘bold’}See Fonts.
titleAlignstring‘left’Horizontal alignment of the title text lines. more…
titleSpacingnumber2Spacing to add to top and bottom of each title line.
titleMarginBottomnumber6Margin to add on bottom of title section.
bodyColorColor‘#fff’Color of body text.
bodyFontFont{}See Fonts.
bodyAlignstring‘left’Horizontal alignment of the body text lines. more…
bodySpacingnumber2Spacing to add to top and bottom of each tooltip item.
footerColorColor‘#fff’Color of footer text.
footerFontFont{style: ‘bold’}See Fonts.
footerAlignstring‘left’Horizontal alignment of the footer text lines. more…
footerSpacingnumber2Spacing to add to top and bottom of each footer line.
footerMarginTopnumber6Margin to add before drawing the footer.
paddingPadding6Padding inside the tooltip.
caretPaddingnumber2Extra distance to move the end of the tooltip arrow away from the tooltip point.
caretSizenumber5Size, in px, of the tooltip arrow.
cornerRadiusnumber6Radius of tooltip corner curves.
multiKeyBackgroundColor‘#fff’Color to draw behind the colored boxes when multiple items are in the tooltip.
displayColorsbooleantrueIf true, color boxes are shown in the tooltip.
boxWidthnumberbodyFont.sizeWidth of the color box if displayColors is true.
boxHeightnumberbodyFont.sizeHeight of the color box if displayColors is true.
usePointStylebooleanfalseUse the corresponding point style (from dataset options) instead of color boxes, ex: star, triangle etc. (size is based on the minimum value between boxWidth and boxHeight).
borderColorColor‘rgba(0, 0, 0, 0)’Color of the border.
borderWidthnumber0Size of the border.
rtlbooleantrue for rendering the tooltip from right to left.
textDirectionstringcanvas’ defaultThis will force the text direction ‘rtl’ or ‘ltr on the canvas for rendering the tooltips, regardless of the css specified on the canvas

Position Modes

Possible modes are:

  • 'average'
  • 'nearest'

'average' mode will place the tooltip at the average position of the items displayed in the tooltip. 'nearest' will place the tooltip at the position of the element closest to the event position.

New modes can be defined by adding functions to the Chart.Tooltip.positioners map.

Example:

  1. /**
  2. * Custom positioner
  3. * @function Tooltip.positioners.myCustomPositioner
  4. * @param elements {Chart.Element[]} the tooltip elements
  5. * @param eventPosition {Point} the position of the event in canvas coordinates
  6. * @returns {Point} the tooltip position
  7. */
  8. const tooltipPlugin = Chart.registry.getPlugin('tooltip');
  9. tooltipPlugin.positioners.myCustomPositioner = function(elements, eventPosition) {
  10. /** @type {Tooltip} */
  11. var tooltip = this;
  12. /* ... */
  13. return {
  14. x: 0,
  15. y: 0
  16. };
  17. };

Alignment

The titleAlign, bodyAlign and footerAlign options define the horizontal position of the text lines with respect to the tooltip box. The following values are supported.

  • 'left' (default)
  • 'right'
  • 'center'

These options are only applied to text lines. Color boxes are always aligned to the left edge.

Sort Callback

Allows sorting of tooltip items. Must implement at minimum a function that can be passed to Array.prototype.sortTooltip - 图1 (opens new window). This function can also accept a third parameter that is the data object passed to the chart.

Filter Callback

Allows filtering of tooltip items. Must implement at minimum a function that can be passed to Array.prototype.filterTooltip - 图2 (opens new window). This function can also accept a fourth parameter that is the data object passed to the chart.

Tooltip Callbacks

Namespace: options.plugins.tooltip.callbacks, the tooltip has the following callbacks for providing text. For all functions, this will be the tooltip object created from the Tooltip constructor.

Namespace: data.datasets[].tooltip.callbacks, items marked with Yes in the column Dataset override can be overridden per dataset.

All functions are called with the same arguments: a tooltip item context. All functions must return either a string or an array of strings. Arrays of strings are treated as multiple lines of text.

NameArgumentsDataset overrideDescription
beforeTitleTooltipItem[], objectReturns the text to render before the title.
titleTooltipItem[], objectReturns text to render as the title of the tooltip.
afterTitleTooltipItem[], objectReturns text to render after the title.
beforeBodyTooltipItem[], objectReturns text to render before the body section.
beforeLabelTooltipItem, objectYesReturns text to render before an individual label. This will be called for each item in the tooltip.
labelTooltipItem, objectYesReturns text to render for an individual item in the tooltip. more…
labelColorTooltipItem, ChartYesReturns the colors to render for the tooltip item. more…
labelTextColorTooltipItem, ChartYesReturns the colors for the text of the label for the tooltip item.
labelPointStyleTooltipItem, ChartYesReturns the point style to use instead of color boxes if usePointStyle is true (object with values pointStyle and rotation). Default implementation uses the point style from the dataset points. more…
afterLabelTooltipItem, objectYesReturns text to render after an individual label.
afterBodyTooltipItem[], objectReturns text to render after the body section.
beforeFooterTooltipItem[], objectReturns text to render before the footer section.
footerTooltipItem[], objectReturns text to render as the footer of the tooltip.
afterFooterTooltipItem[], objectText to render after the footer section.

Label Callback

The label callback can change the text that displays for a given data point. A common example to show a unit. The example below puts a '$' before every row.

  1. var chart = new Chart(ctx, {
  2. type: 'line',
  3. data: data,
  4. options: {
  5. plugins: {
  6. tooltip: {
  7. callbacks: {
  8. label: function(context) {
  9. var label = context.dataset.label || '';
  10. if (label) {
  11. label += ': ';
  12. }
  13. if (context.parsed.y !== null) {
  14. label += new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(context.parsed.y);
  15. }
  16. return label;
  17. }
  18. }
  19. }
  20. }
  21. }
  22. });

Label Color Callback

For example, to return a red box for each item in the tooltip you could do:

  1. var chart = new Chart(ctx, {
  2. type: 'line',
  3. data: data,
  4. options: {
  5. plugins: {
  6. tooltip: {
  7. callbacks: {
  8. labelColor: function(context) {
  9. return {
  10. borderColor: 'rgb(255, 0, 0)',
  11. backgroundColor: 'rgb(255, 0, 0)'
  12. };
  13. },
  14. labelTextColor: function(context) {
  15. return '#543453';
  16. }
  17. }
  18. }
  19. }
  20. }
  21. });

Label Point Style Callback

For example, to draw triangles instead of the regular color box for each item in the tooltip you could do:

  1. var chart = new Chart(ctx, {
  2. type: 'line',
  3. data: data,
  4. options: {
  5. plugins: {
  6. tooltip: {
  7. usePointStyle: true,
  8. callbacks: {
  9. labelPointStyle: function(context) {
  10. return {
  11. pointStyle: 'triangle',
  12. rotation: 0
  13. };
  14. }
  15. }
  16. }
  17. }
  18. }
  19. });

Tooltip Item Context

The tooltip items passed to the tooltip callbacks implement the following interface.

  1. {
  2. // The chart the tooltip is being shown on
  3. chart: Chart
  4. // Label for the tooltip
  5. label: string,
  6. // Parsed data values for the given `dataIndex` and `datasetIndex`
  7. parsed: object,
  8. // Raw data values for the given `dataIndex` and `datasetIndex`
  9. raw: object,
  10. // Formatted value for the tooltip
  11. formattedValue: string,
  12. // The dataset the item comes from
  13. dataset: object
  14. // Index of the dataset the item comes from
  15. datasetIndex: number,
  16. // Index of this data item in the dataset
  17. dataIndex: number,
  18. // The chart element (point, arc, bar, etc.) for this tooltip item
  19. element: Element,
  20. }

External (Custom) Tooltips

External tooltips allow you to hook into the tooltip rendering process so that you can render the tooltip in your own custom way. Generally this is used to create an HTML tooltip instead of an on-canvas tooltip. The external option takes a function which is passed a context parameter containing the chart and tooltip. You can enable external tooltips in the global or chart configuration like so:

  1. var myPieChart = new Chart(ctx, {
  2. type: 'pie',
  3. data: data,
  4. options: {
  5. plugins: {
  6. tooltip: {
  7. // Disable the on-canvas tooltip
  8. enabled: false,
  9. external: function(context) {
  10. // Tooltip Element
  11. var tooltipEl = document.getElementById('chartjs-tooltip');
  12. // Create element on first render
  13. if (!tooltipEl) {
  14. tooltipEl = document.createElement('div');
  15. tooltipEl.id = 'chartjs-tooltip';
  16. tooltipEl.innerHTML = '<table></table>';
  17. document.body.appendChild(tooltipEl);
  18. }
  19. // Hide if no tooltip
  20. var tooltipModel = context.tooltip;
  21. if (tooltipModel.opacity === 0) {
  22. tooltipEl.style.opacity = 0;
  23. return;
  24. }
  25. // Set caret Position
  26. tooltipEl.classList.remove('above', 'below', 'no-transform');
  27. if (tooltipModel.yAlign) {
  28. tooltipEl.classList.add(tooltipModel.yAlign);
  29. } else {
  30. tooltipEl.classList.add('no-transform');
  31. }
  32. function getBody(bodyItem) {
  33. return bodyItem.lines;
  34. }
  35. // Set Text
  36. if (tooltipModel.body) {
  37. var titleLines = tooltipModel.title || [];
  38. var bodyLines = tooltipModel.body.map(getBody);
  39. var innerHtml = '<thead>';
  40. titleLines.forEach(function(title) {
  41. innerHtml += '<tr><th>' + title + '</th></tr>';
  42. });
  43. innerHtml += '</thead><tbody>';
  44. bodyLines.forEach(function(body, i) {
  45. var colors = tooltipModel.labelColors[i];
  46. var style = 'background:' + colors.backgroundColor;
  47. style += '; border-color:' + colors.borderColor;
  48. style += '; border-width: 2px';
  49. var span = '<span style="' + style + '"></span>';
  50. innerHtml += '<tr><td>' + span + body + '</td></tr>';
  51. });
  52. innerHtml += '</tbody>';
  53. var tableRoot = tooltipEl.querySelector('table');
  54. tableRoot.innerHTML = innerHtml;
  55. }
  56. var position = context.chart.canvas.getBoundingClientRect();
  57. var bodyFont = Chart.helpers.toFont(tooltipModel.options.bodyFont);
  58. // Display, position, and set styles for font
  59. tooltipEl.style.opacity = 1;
  60. tooltipEl.style.position = 'absolute';
  61. tooltipEl.style.left = position.left + window.pageXOffset + tooltipModel.caretX + 'px';
  62. tooltipEl.style.top = position.top + window.pageYOffset + tooltipModel.caretY + 'px';
  63. tooltipEl.style.font = bodyFont.string;
  64. tooltipEl.style.padding = tooltipModel.padding + 'px ' + tooltipModel.padding + 'px';
  65. tooltipEl.style.pointerEvents = 'none';
  66. }
  67. }
  68. }
  69. }
  70. });

See samplesTooltip - 图3 (opens new window) for examples on how to get started with external tooltips.

Tooltip Model

The tooltip model contains parameters that can be used to render the tooltip.

  1. {
  2. // The items that we are rendering in the tooltip. See Tooltip Item Interface section
  3. dataPoints: TooltipItem[],
  4. // Positioning
  5. xAlign: string,
  6. yAlign: string,
  7. // X and Y properties are the top left of the tooltip
  8. x: number,
  9. y: number,
  10. width: number,
  11. height: number,
  12. // Where the tooltip points to
  13. caretX: number,
  14. caretY: number,
  15. // Body
  16. // The body lines that need to be rendered
  17. // Each object contains 3 parameters
  18. // before: string[] // lines of text before the line with the color square
  19. // lines: string[], // lines of text to render as the main item with color square
  20. // after: string[], // lines of text to render after the main lines
  21. body: object[],
  22. // lines of text that appear after the title but before the body
  23. beforeBody: string[],
  24. // line of text that appear after the body and before the footer
  25. afterBody: string[],
  26. // Title
  27. // lines of text that form the title
  28. title: string[],
  29. // Footer
  30. // lines of text that form the footer
  31. footer: string[],
  32. // colors to render for each item in body[]. This is the color of the squares in the tooltip
  33. labelColors: Color[],
  34. labelTextColors: Color[],
  35. // 0 opacity is a hidden tooltip
  36. opacity: number,
  37. // tooltip options
  38. options : Object
  39. }