Chart.js

repository·master·Indexed 13 days ago

https://github.com/chartjs/chart.js

A flexible JavaScript library for creating HTML5 data visualizations and charts using the canvas element. Version 4.5.1 provides a wide range of configurable chart types, including linear, logarithmic, category, time, and timeseries Cartesian axes.

Tokens
110.2K
Snippets
314
Records
433
Agent score
99%

What's inside Chart.js

  1. Overview of Chart.js

    master
    Chart.js is a simple yet flexible JavaScript library designed for designers and developers to create charts. It provides a wide range of chart types and is highly configurable. The current documentation and library version is v4.
  2. Core features and customization of Chart.js

    master

    Chart.js provides several key capabilities for data visualization:

    • Built-in Chart Types: A variety of standard charts (e.g., area charts) are available out of the box.
    • Mixed Charts: You can combine multiple chart types into a single visualization on the same canvas.
    • Plugins: Extend functionality using custom or community-maintained plugins for features like annotations, zooming, or drag-and-drop.
    • Customization: Highly configurable via a sound default configuration and extensive options for styling and animations.
  3. Use multiple datasets in a single chart

    master

    Chart.js supports multiple datasets for most chart types. You can provide an array of objects to the datasets property. Each dataset is plotted independently and can be toggled via the legend.

    data: {
      labels: ['Jan', 'Feb', 'Mar'],
      datasets: [
        {
          label: 'Dataset 1',
          data: [10, 20, 30]
        },
        {
          label: 'Dataset 2',
          data: [5, 15, 25]
        }
      ]
    }
  4. Configure Chart.js Interaction Modes

    master

    Interaction modes determine how Chart.js detects elements during hover or touch events (e.g., for tooltips). You can configure these via the options.interaction object.

    Key properties include:

    • mode: Defines the algorithm used to find elements. Common values include 'index', 'dataset', 'point', 'nearest', 'x', and 'y'.
    • axis: Determines the axis used for interaction (e.g., 'x', 'y', or 'xy').
    • intersect: A boolean that determines whether the interaction should only trigger when the cursor is directly intersecting an element (set to false to trigger based on proximity/axis alignment).

    To apply changes dynamically, update the chart.options.interaction object and call chart.update().

    const config = {
      type: 'line',
      data: data,
      options: {
        interaction: {
          intersect: false,
          mode: 'index',
          axis: 'x'
        }
      }
    };
    
    // To update dynamically:
    chart.options.interaction.mode = 'nearest';
    chart.update();
  5. Configure element-level styling for all datasets

    master

    While dataset-specific settings allow for individual styling, you can use Element Configuration to style all objects of a specific type (e.g., all bars or all points) the same way. This is useful for applying a uniform border color across all datasets while allowing individual fill colors.

    Element options can be configured in two ways:

    1. Per Chart: Using the options.elements.<type> namespace in your chart configuration.
    2. Globally: Modifying Chart.defaults.elements.<type> to affect every chart instance in your application.

    Supported element types are: arc, line, point, and bar.

    // Set the border width of all bar charts globally
    Chart.defaults.elements.bar.borderWidth = 2;
  6. Format data for Scatter Charts

    master

    Unlike line charts which support multiple data formats, scatter charts strictly require data to be provided in a point format. Each data point must be an object containing x and y keys. Because the x-axis is a linear scale, the values for x and y must be numbers or strings that are parsable as numbers.

    data: [{
        x: 10,
        y: 20
    }, {
        x: 15,
        y: 10
    }]
  7. Configure Bubble Chart data structure

    master

    Bubble chart datasets require a data array where each element is an object representing a point. Each point must contain the following properties:

    • x: The horizontal axis value.
    • y: The vertical axis value.
    • r: The bubble radius in pixels.

    Note: The r property is not scaled by the chart; it represents the raw pixel radius used to draw the bubble on the canvas.

    {
        x: number,
        y: number,
        r: number
    }
  8. Use scriptable options for dynamic styling

    master

    Chart.js allows you to pass a function to many configuration options (like borderColor, backgroundColor, borderWidth, etc.). These are called Scriptable Options.

    When a function is provided, Chart.js calls it for every element in the dataset. The function receives a context object which contains:

    • chart: The chart instance.
    • datasetIndex: The index of the dataset.
    • dataIndex: The index of the specific data point.
    • raw: The raw data value.
    • parsed: The parsed data value.

    This is the recommended way to implement gradients or colors that change based on the data value or the chart's dimensions.

  9. Data Structure for Polar Area Charts

    master

    A Polar Area chart requires a data object with:

    1. datasets: An array of objects, where each object contains a data array of numbers. Chart.js calculates the relative proportions based on these values.
    2. labels: An array of strings. These labels are used in the legend and in tooltips when hovering over specific arcs.
    data = {
        datasets: [{
            data: [10, 20, 30]
        }],
        labels: [
            'Red',
            'Yellow',
            'Blue'
        ]
    };
  10. Create and use custom plugins

    master

    Plugins allow you to extend Chart.js functionality by hooking into the chart lifecycle. A plugin is an object with a name (or id) and callback functions (e.g., beforeDraw, afterDraw).

    To use a plugin:

    1. Define the plugin object.
    2. Pass it to the plugins array in the Chart constructor, OR
    3. Configure its specific options under options.plugins.[pluginId].
    const myPlugin = {
      id: 'myCustomPlugin',
      beforeDraw(chart, args, options) {
        // Access canvas context via chart.ctx
        // Use options provided in the chart config
      }
    };
    
    new Chart(ctx, {
      plugins: [myPlugin],
      options: {
        plugins: {
          myCustomPlugin: {
            borderColor: 'red'
          }
        }
      }
    });
  11. Use scriptable options for animations

    master

    Chart.js supports Scriptable Options, allowing you to define configuration values as functions. This is particularly useful for animations where the delay, duration, or starting position (from) depends on the data context (ctx).

    When using a function for an animation property, the ctx (context) object provides access to:

    • ctx.index: The index of the current element.
    • ctx.datasetIndex: The index of the dataset.
    • ctx.type: The type of animation (e.g., 'data').
    • ctx.chart: The chart instance.
    • ctx.chart.scales: Access to scale methods like getPixelForValue.
    • ctx.chart.getDatasetMeta(index): Access to metadata for a specific dataset, useful for retrieving the properties of previous elements.