chartjs-plugin-datalabels

repository·master·Indexed 21 days ago

https://github.com/chartjs/chartjs-plugin-datalabels

A highly customizable plugin for Chart.js 3.x and higher designed to display labels on data points across all standard chart types, including bar, line, doughnut, and radar. It features scriptable options for dynamic appearance and positioning, support for interactive label events (enter, leave, click), and a formatter for transforming data values or displaying custom text and multiline labels.

Tokens
18.3K
Snippets
49
Records
57
Agent score
71%

What's inside chartjs-plugin-datalabels

  1. Define multiple labels per data element

    master

    By default, the plugin creates a single label per data element. You can define multiple distinct labels for each data element using the labels option within the datalabels plugin configuration.

    The labels option is an object where:

    • Each key represents a unique label identifier.
    • Each value is an object containing configuration options specific to that label.

    These label-specific options are merged on top of options defined at both the chart level and the dataset level.

    {
      options: {
        plugins: {
          datalabels: {
            color: 'blue', // Default color for all labels
            labels: {
              title: {
                font: {
                  weight: 'bold'
                }
              },
              value: {
                color: 'green'
              }
            }
          }
        }
      }
    }
  2. Avoid using private properties and methods

    master

    The plugin does not expose a public API other than its configuration options.

    Warning: Do not access private properties or methods that start with $ or _. This includes the $datalabels property attached to Chart.js objects. Relying on these internal implementation details may cause your production build to break in future minor or patch releases without notice.

  3. Key features of chartjs-plugin-datalabels

    master

    The plugin provides three core capabilities for developers:

    • Flexible Compatibility: Works with all Chart.js chart types (bar, line, doughnut, radar, etc.).
    • Full Customization: The appearance and position of every label can be controlled dynamically.
    • Interactivity: Labels can react to user interactions or element events through the use of scriptable options.
  4. Register label event listeners

    master

    Use the listeners option to register callbacks that trigger when a label event is detected. The listeners object uses event names as keys and callback functions as values.

    Callback Arguments

    Each callback receives two arguments:

    1. context: An object containing label information (similar to scriptable options). You can modify this object to store state.
    2. event: The Chart.js event object (e.g., containing x, y, and native properties).

    Triggering Re-renders

    If a listener callback explicitly returns true, the context is updated with any modifications you made, and the chart is re-rendered. This is the standard way to implement visual interactions like highlighting or selection.

    Configuration Scope

    Listeners can be scoped in two ways:

    • Global (Plugin-wide): Registered under options.plugins.datalabels.listeners. These apply to all labels in the chart.
    • Dataset-specific: Registered under dataset.datalabels.listeners. These apply only to labels within that specific dataset.

    Note: If no listeners are registered, incoming events are ignored, ensuring no performance penalty for charts that do not use interactivity.

    // Example of a dataset-specific listener
    { 
      datasets: [{
        datalabels: {
          listeners: {
            click: function(context, event) {
              console.log('Clicked label index:', context.dataIndex);
            }
          }
        }
      }]
    }
  5. Understand the Option Context object

    master

    When using scriptable options or the formatter function, you receive a context object. This object provides the necessary metadata to resolve options dynamically based on the state of the chart and the specific data point being processed.

    | Property | Type | Description |
    | -------- | ---- | ----------- |
    | `active` | `bool` | Whether the associated element is hovered ([see interactions](https://www.chartjs.org/docs/latest/configuration/interactions.html)) |
    | `chart` | `Chart` | The associated chart |
    | `dataIndex` | `number` | The index of the associated data |
    | `dataset` | `object` | The dataset at index `datasetIndex` |
    | `datasetIndex` | `number` | The index of the associated dataset |
  6. Use Scriptable Options for dynamic styling

    master

    Scriptable options allow you to pass a function instead of a static value. This function is called for each data element and receives a context object containing information about the specific data point, dataset, and chart. This is useful for coloring labels based on their values (e.g., red for negative, green for positive).

    color: function(context) {
      var index = context.dataIndex;
      var value = context.dataset.data[index];
      return value < 0 ? 'red' :  // draw negative values in red
        index % 2 ? 'blue' :      // else, alternate values in blue and green
        'green';
    }
  7. Use the built-in Context type for TypeScript

    master

    The plugin includes bundled TypeScript type declarations. You can import the Context type to provide type safety for option callbacks (like rotation) that receive a context object as an argument.

    import {Context} from 'chartjs-plugin-datalabels';
    
    const chart = new Chart('foo', { 
      options: {
        plugins: {
          datalabels: {
            rotation: (ctx: Context) => {
              return ctx.dataIndex % 2 ? 180 : 0;
            },
          }
        }
      }
    });
  8. Remove a label from a specific dataset

    master

    To prevent a globally defined label from appearing on a specific dataset, set its key to null within the dataset's datalabels.labels configuration.

    {
      data: {
        datasets: [{
          // First dataset: uses the global 'title' label
        }, {
          // Second dataset: removes the 'title' label
          datalabels: {
            labels: {
              title: null
            }
          }
        }]
      },
      options: {
        plugins: {
          datalabels: {
            labels: {
              title: {
                color: 'blue'
              }
            }
          }
        }
      }
    }
  9. Modify existing labels for specific datasets

    master

    You can override or modify specific labels for a single dataset by providing a labels object within the dataset's datalabels configuration. Use the same key as defined in the global plugin options.

    Important Priority Rule: Options defined under labels.<key> always take precedence over options defined at the chart level or the dataset level. For example, if you set a color at the dataset level but a different color inside labels.title, the labels.title color will be used.

    {
      data: {
        datasets: [{
          // First dataset: modifies global datalabels color to yellow
          datalabels: {
            color: 'yellow'
          }
        }, {
          // Second dataset: modifies the 'title' label color specifically
          datalabels: {
            labels: {
              title: {
                color: 'green'
              }
            }
          }
        }]
      },
      options: {
        plugins: {
          datalabels: {
            color: 'pink',
            labels: {
              value: {},
              title: {
                color: 'blue'
              }
            }
          }
        }
      }
    }