chartjs-plugin-datalabels

website·Indexed 30 days ago

https://chartjs-plugin-datalabels.netlify.app/

A highly customizable Chart.js plugin used to display labels on all chart types, including bar, line, doughnut, and radar. The documentation covers installation, label positioning, formatting, event listeners, TypeScript type declarations, and migration to v1.0.0.

Tokens
5.9K
Snippets
37
Records
45
Agent score
74%

What's inside chartjs-plugin-datalabels

  1. Overview of chartjs-plugin-datalabels

    The chartjs-plugin-datalabels is a highly customizable plugin for Chart.js that allows developers to display labels directly on data for any type of chart. It requires Chart.js version 3.x or higher to function.
  2. Overview of chartjs-plugin-datalabels capabilities

    The chartjs-plugin-datalabels plugin provides flexible and customizable data labels for Chart.js. It is compatible with all chart types, including bar, line, doughnut, and radar charts. Key features include fully dynamic control over the appearance and position of labels, as well as the ability to make labels interactive by reacting to user interactions or element events via scriptable options.
  3. Reference the Option Context object

    The context object is provided to scriptable options and formatter functions to give contextual information about the data element. It can be extended dynamically with custom properties for event-based customizations.

    /* Context Object Properties:

    • active (bool): Whether the associated element is hovered.
    • chart (Chart): The associated chart instance.
    • dataIndex (number): The index of the associated data point.
    • dataset (object): The dataset object at index datasetIndex.
    • datasetIndex (number): The index of the associated dataset. */
  4. Use Scriptable Options for dynamic label styling

    Many options in the chartjs-plugin-datalabels plugin are 'scriptable', meaning they accept a function instead of a static value. This function is executed for each data point and receives a context object containing metadata about the specific element being drawn, allowing for conditional styling based on data values or indices.
    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';
    }
  5. Integrate chartjs-plugin-datalabels into a project

    The plugin can be integrated using standard HTML script tags or as a JavaScript module. When using HTML, the plugin must be loaded AFTER the Chart.js library. When using a CDN, the plugin is available under the global ChartDataLabels property.
    <!-- HTML Integration -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@3.0.0/dist/chart.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0"></script>
    // Module Integration
    import { Chart } from 'chart.js';
    import ChartDataLabels from 'chartjs-plugin-datalabels';
  6. Modify, add, or remove labels for specific datasets

    You can control which labels appear on specific datasets by using the datalabels.labels object within the dataset configuration.

    • Modifying: Use an existing label key to override options for that specific dataset.
    • Adding: Use a new, non-existent label key to add a label only to that dataset.
    • Removing: Set a label key to null to prevent that specific label from appearing on the dataset.

    Important: Options defined under labels.<key> always take precedence over general chart and dataset level options.

    {
      data: {
        datasets: [{
          // First dataset: inherits global 'title' label
        }, {
          // Second dataset: overrides 'title' color and adds 'value' label
          datalabels: {
            labels: {
              title: { color: 'green' },
              value: { color: 'green' }
            }
          }
        }, {
          // Third dataset: removes the 'title' label
          datalabels: {
            labels: {
              title: null
            }
          }
        }]
      },
      options: {
        plugins: {
          datalabels: {
            labels: {
              title: { color: 'blue' }
            }
          }
        }
      }
    }
  7. Register chartjs-plugin-datalabels for v1.0.0

    In version 1.0.0, the plugin must be manually registered. You can register it globally for all charts or locally for a specific chart instance.
    // Global registration
    Chart.plugins.register(ChartDataLabels);
    
    // Local registration
    new Chart('foo', {
      plugins: [ChartDataLabels]
    });
  8. Use Indexable Options for per-element styling

    Indexable options allow you to provide an array of values where each item corresponds to the data element at the same index. This is an alternative to scriptable functions, though it requires providing a value for every data point in the set.
    color: [
      'red',    // color for data at index 0
      'blue',   // color for data at index 1
      'green',  // color for data at index 2
      'black',  // color for data at index 3
      //...
    ]
  9. Extend the datalabels Context using Module Augmentation

    Use TypeScript module augmentation to globally extend the Context interface. This method applies the custom properties to all charts in the project. Use this only if all charts should share the same extended context declaration.
    // shims-chartjs-plugin-datalabels.d.ts
    import { Context } from 'chartjs-plugin-datalabels';
    
    declare module 'chartjs-plugin-datalabels' {
      interface Context {
        foo?: number;
      }
    }
    
    // index.ts
    import { Context } from 'chartjs-plugin-datalabels';
    
    const chart = new Chart('foo', {
      options: {
        plugins: {
          datalabels: {
            rotation: (ctx: Context) => ctx.foo || 0,
            listeners: {
              click: (ctx: Context) => {
                ctx.foo += (ctx.foo || 0) + 10;
                return true;
              }
            }
          }
        }
      }
    });
  10. Register chartjs-plugin-datalabels for v2.0.0 (Chart.js v3)

    Due to changes in Chart.js v3, the registration method has changed. Use Chart.register() instead of Chart.plugins.register().
    import {Chart} from 'chart.js';
    import ChartDataLabels from 'chartjs-plugin-datalabels';
    
    Chart.register(ChartDataLabels);
  11. Extend the datalabels Context using a Custom Interface

    To add custom properties to the plugin context for a specific chart, create a custom interface that extends the base Context type. This approach is recommended when different charts require different context declarations.
    import { Context } from 'chartjs-plugin-datalabels';
    
    interface FooContext extends Context {
      foo?: number;
    }
    
    const chart = new Chart('foo', {
      options: {
        plugins: {
          datalabels: {
            rotation: (ctx: FooContext) => ctx.foo || 0,
            listeners: {
              click: (ctx: FooContext) => {
                ctx.foo += (ctx.foo || 0) + 10;
                return true;
              }
            }
          }
        }
      }
    });
  12. Create multiline data labels

    To display labels on multiple lines, the formatter should return a string containing the newline character (\n) or an array of strings where each element represents a new line. The vertical spacing between lines can be adjusted using the font.lineHeight option.
    formatter: function(value) {
      // Using newline character
      return 'line1\nline2\n' + value;
      
      // OR using an array of strings
      // return ['line1', 'line2', value];
    }