Tooltip

Tooltip Configuration

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

WARNING

The bubble, doughnut, pie, polar area, and scatter charts override the tooltip defaults. To change the overrides for those chart types, the options are defined in Chart.overrides[type].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{weight: ‘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{weight: ‘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.
cornerRadiusnumber|object6Radius 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.
boxPaddingnumber1Padding between the color box and the text.
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
xAlignstringundefinedPosition of the tooltip caret in the X direction. more
yAlignstringundefinedPosition of the tooltip caret in the Y direction. more

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.

You can also define custom position modes.

Tooltip Alignment

The xAlign and yAlign options define the position of the tooltip caret. If these parameters are unset, the optimal caret position is determined.

The following values for the xAlign setting are supported.

  • 'left'
  • 'center'
  • 'right'

The following values for the yAlign setting are supported.

  • 'top'
  • 'center'
  • 'bottom'

Text 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.

A tooltip item context is generated for each item that appears in the tooltip. This is the primary model that the callback methods interact with. For functions that return text, arrays of strings are treated as multiple lines of text.

NameArgumentsReturn TypeDataset overrideDescription
beforeTitleTooltipItem[]string | string[]Returns the text to render before the title.
titleTooltipItem[]string | string[]Returns text to render as the title of the tooltip.
afterTitleTooltipItem[]string | string[]Returns text to render after the title.
beforeBodyTooltipItem[]string | string[]Returns text to render before the body section.
beforeLabelTooltipItemstring | string[]YesReturns text to render before an individual label. This will be called for each item in the tooltip.
labelTooltipItemstring | string[]YesReturns text to render for an individual item in the tooltip. more…
labelColorTooltipItemobjectYesReturns the colors to render for the tooltip item. more…
labelTextColorTooltipItemColorYesReturns the colors for the text of the label for the tooltip item.
labelPointStyleTooltipItemobjectYesReturns 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…
afterLabelTooltipItemstring | string[]YesReturns text to render after an individual label.
afterBodyTooltipItem[]string | string[]Returns text to render after the body section.
beforeFooterTooltipItem[]string | string[]Returns text to render before the footer section.
footerTooltipItem[]string | string[]Returns text to render as the footer of the tooltip.
afterFooterTooltipItem[]string | string[]Text 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. const chart = new Chart(ctx, {
  2. type: 'line',
  3. data: data,
  4. options: {
  5. plugins: {
  6. tooltip: {
  7. callbacks: {
  8. label: function(context) {
  9. let 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 with a blue dashed border that has a border radius for each item in the tooltip you could do:

  1. const 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(0, 0, 255)',
  11. backgroundColor: 'rgb(255, 0, 0)',
  12. borderWidth: 2,
  13. borderDash: [2, 2],
  14. borderRadius: 2,
  15. };
  16. },
  17. labelTextColor: function(context) {
  18. return '#543453';
  19. }
  20. }
  21. }
  22. }
  23. }
  24. });

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. const 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. const 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. let 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. const 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. const titleLines = tooltipModel.title || [];
  38. const bodyLines = tooltipModel.body.map(getBody);
  39. let 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. const colors = tooltipModel.labelColors[i];
  46. let style = 'background:' + colors.backgroundColor;
  47. style += '; border-color:' + colors.borderColor;
  48. style += '; border-width: 2px';
  49. const span = '<span style="' + style + '"></span>';
  50. innerHtml += '<tr><td>' + span + body + '</td></tr>';
  51. });
  52. innerHtml += '</tbody>';
  53. let tableRoot = tooltipEl.querySelector('table');
  54. tableRoot.innerHTML = innerHtml;
  55. }
  56. const position = context.chart.canvas.getBoundingClientRect();
  57. const 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 samples 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. chart: Chart,
  3. // The items that we are rendering in the tooltip. See Tooltip Item Interface section
  4. dataPoints: TooltipItem[],
  5. // Positioning
  6. xAlign: string,
  7. yAlign: string,
  8. // X and Y properties are the top left of the tooltip
  9. x: number,
  10. y: number,
  11. width: number,
  12. height: number,
  13. // Where the tooltip points to
  14. caretX: number,
  15. caretY: number,
  16. // Body
  17. // The body lines that need to be rendered
  18. // Each object contains 3 parameters
  19. // before: string[] // lines of text before the line with the color square
  20. // lines: string[], // lines of text to render as the main item with color square
  21. // after: string[], // lines of text to render after the main lines
  22. body: object[],
  23. // lines of text that appear after the title but before the body
  24. beforeBody: string[],
  25. // line of text that appear after the body and before the footer
  26. afterBody: string[],
  27. // Title
  28. // lines of text that form the title
  29. title: string[],
  30. // Footer
  31. // lines of text that form the footer
  32. footer: string[],
  33. // colors to render for each item in body[]. This is the color of the squares in the tooltip
  34. labelColors: Color[],
  35. labelTextColors: Color[],
  36. // 0 opacity is a hidden tooltip
  37. opacity: number,
  38. // tooltip options
  39. options: Object
  40. }

Custom Position Modes

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

Example:

  1. import { Tooltip } from 'chart.js';
  2. /**
  3. * Custom positioner
  4. * @function Tooltip.positioners.myCustomPositioner
  5. * @param elements {Chart.Element[]} the tooltip elements
  6. * @param eventPosition {Point} the position of the event in canvas coordinates
  7. * @returns {TooltipPosition} the tooltip position
  8. */
  9. Tooltip.positioners.myCustomPositioner = function(elements, eventPosition) {
  10. // A reference to the tooltip model
  11. const tooltip = this;
  12. /* ... */
  13. return {
  14. x: 0,
  15. y: 0
  16. // You may also include xAlign and yAlign to override those tooltip options.
  17. };
  18. };
  19. // Then, to use it...
  20. new Chart.js(ctx, {
  21. data,
  22. options: {
  23. plugins: {
  24. tooltip: {
  25. position: 'myCustomPositioner'
  26. }
  27. }
  28. }
  29. })

See samples for a more detailed example.

If you’re using TypeScript, you’ll also need to register the new mode:

  1. declare module 'chart.js' {
  2. interface TooltipPositionerMap {
  3. myCustomPositioner: TooltipPositionerFunction<ChartType>;
  4. }
  5. }