Chart.js - Documentation

Getting Started

Installation

Chart.js can be integrated into your project using several methods:

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
npm install chart.js

Then, import it into your JavaScript file:

import { Chart, registerables } from 'chart.js';
Chart.register(...registerables);
yarn add chart.js

And then import similarly to the npm example.

Basic Chart Example

This example demonstrates creating a simple bar chart:

<!DOCTYPE html>
<html>
<head>
  <title>Chart.js Example</title>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> </head>
<body>
  <canvas id="myChart"></canvas>
  <script>
    const ctx = document.getElementById('myChart').getContext('2d');
    const myChart = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
          label: '# of Votes',
          data: [12, 19, 3, 5, 2, 3],
          backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)',
            'rgba(153, 102, 255, 0.2)',
            'rgba(255, 159, 64, 0.2)'
          ],
          borderColor: [
            'rgba(255, 99, 132, 1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)',
            'rgba(153, 102, 255, 1)',
            'rgba(255, 159, 64, 1)'
          ],
          borderWidth: 1
        }]
      },
      options: {
        scales: {
          y: {
            beginAtZero: true
          }
        }
      }
    });
  </script>
</body>
</html>

Including Chart.js in your project

After installing Chart.js (using one of the methods described above), you need to include it in your project. For CDN inclusion, the <script> tag is sufficient. For npm or yarn installations, you’ll need to import it into your Javascript file as shown in the Installation section. Ensure that the script tag (for CDN) or the import statement (for npm/yarn) is placed after the <canvas> element in your HTML, or ensure proper asynchronous loading mechanisms are implemented.

First steps with Chart.js

Once included, creating a chart involves these basic steps:

  1. Get the canvas element: Obtain a reference to the <canvas> element where the chart will be rendered using document.getElementById('yourCanvasId').getContext('2d');. Replace yourCanvasId with the actual ID of your canvas.

  2. Create a new Chart instance: Instantiate a new Chart object, providing the canvas context and a configuration object. The configuration includes the chart type ('bar', 'line', 'pie', etc.), data (labels and datasets), and options (like title, legend, scales, etc.).

  3. Customize (optional): Explore the extensive options available to customize the chart’s appearance, behavior, and data representation. The Chart.js documentation provides comprehensive details on chart types and customization options.

Remember to replace placeholders like 'yourCanvasId' with your actual element IDs. Consult the Chart.js documentation for detailed information on data structures, configuration options, and available chart types.

Chart Types

Line Charts

Line charts are used to display data as a series of points connected by straight lines. They’re ideal for showing trends over time or other continuous variables. Key configuration options include:

Bar Charts

Bar charts represent data as rectangular bars, making comparisons between categories easy. They can be vertical or horizontal. Key configuration options include:

Pie and Doughnut Charts

Pie and doughnut charts display proportions of a whole. A doughnut chart leaves a hole in the center. Key configuration options include:

Scatter Charts

Scatter charts display data as individual points, useful for showing relationships between two variables. Key configuration options include:

Bubble Charts

Bubble charts are an extension of scatter charts where the size of each point represents a third variable. Configuration is similar to scatter charts, with the addition of:

Radar Charts

Radar charts (also known as star charts) display data as a series of points connected by lines, forming a polygon. Useful for comparing multiple variables against a central point. Key configuration options include:

Polar Area Charts

Polar area charts are similar to radar charts, but the area enclosed by the lines is filled with color. The area of each segment is proportional to its value. Key configuration options are similar to radar charts, focusing on data representation and visual styling. Remember that the area, not just the length of the lines, represents the data values.

Chart Configuration

Data Structure

Chart.js uses a consistent data structure across all chart types. The core components are:

The structure is flexible and adapts to the chart type. For example, scatter charts use x and y coordinates within the data array, and bubble charts also include a radius value.

Chart Options

Chart options provide extensive control over the chart’s appearance and behavior. These options are passed as a single object to the Chart constructor. Key option categories include:

Scales (Axes)

Scales define the axes of the chart. Options are specified within the options.scales object. You can configure separate options for x and y axes (and even additional axes for certain chart types). Common options include:

Legends

Legends display labels for each dataset in the chart. They can be customized through:

Titles

Chart titles are configured using:

Tooltips

Tooltips provide interactive information when hovering over data points. They are customized through:

Plugins

Plugins extend Chart.js’s functionality. They’re registered using Chart.register(plugin), and configured within options.plugins. Plugins add features like annotations, zoom/pan, data export, and more. Refer to the plugin’s specific documentation for configuration details.

Responsive Design

Chart.js is responsive by default (responsive: true). The chart automatically adjusts its size to fit its container. You can control aspect ratio using maintainAspectRatio.

Animations

Chart animations can be customized using the options.animation object. Key options include:

Data Handling

Working with datasets

Datasets are the core of your chart data. They’re managed within the data.datasets array. Each dataset is an object, and you can add, remove, or modify datasets to dynamically update the chart.

Updating Charts

After modifying the chart’s data or configuration, you must update the chart to reflect the changes. This is done using the chart.update() method. For example:

// ... chart creation code ...

// Modify data
myChart.data.datasets[0].data = [10, 20, 30, 40];

// Update the chart
myChart.update();

The update() method redraws the chart with the new data. You can optionally pass a configuration object to update() to control the animation during the update process.

Data labels and formatting

Data labels are usually handled automatically by Chart.js based on the chart type. However, you can significantly customize them.

Handling large datasets

Chart.js handles large datasets relatively efficiently, but performance can degrade for extremely large datasets (thousands or tens of thousands of data points). Optimization strategies include:

Real-time data updates

Updating charts with real-time data requires continuous updates using chart.update(). Common approaches include:

Remember that frequent updates can significantly impact performance. Choose your approach carefully based on the data frequency and the desired performance level.

Advanced Techniques

Customizing Charts

Beyond the standard configuration options, Chart.js offers powerful customization capabilities:

Creating reusable chart components

For complex applications or when creating many similar charts, creating reusable components improves code organization and maintainability. This can be done using various techniques:

Chart Interactions

Chart.js provides built-in interaction capabilities (tooltips, hover effects). More advanced interactions can be implemented:

Working with Events

Chart.js emits various events during its lifecycle and in response to user interactions. You can listen for these events and trigger custom actions.

myChart.addEventListener('click', function(event, array){
    // Handle click event
    console.log(event, array);
});

The event object provides context about the interaction, and array contains information about the chart elements involved (if any).

Integrating with other libraries

Chart.js integrates well with other JavaScript libraries:

Remember to check the documentation of both libraries to ensure compatibility and understand how to correctly handle data exchange and event communication.

Scales and Axes

Chart.js offers a variety of built-in scale types to represent data on the axes. The choice of scale depends on the nature of your data and how you want to visualize it. Each scale type has specific options for customization. These options are generally accessed through the options.scales object in the chart configuration.

Linear Scale

The linear scale is the most common scale type, representing data linearly. It is suitable for numerical data that is evenly spaced. Key options include:

Logarithmic Scale

The logarithmic scale is used when data spans several orders of magnitude. It represents data on a logarithmic scale, compressing large ranges of values into a more manageable display. It’s suitable for data with exponential growth or decay. Options similar to linear scales apply, but with some logarithmic-specific additions such as:

Time Scale

The time scale is designed for time-series data. It automatically handles various time units (seconds, minutes, hours, days, etc.) and formats the axis labels accordingly. It’s crucial for effectively representing time-dependent data. Key options include:

Category Scale

The category scale is used for categorical data, where data points are associated with distinct categories rather than numerical values. The labels for each category are taken from data.labels. This scale is commonly used with bar charts, pie charts, and other charts displaying discrete categories. Key options:

Radial Linear Scale

The radial linear scale is used in radar and polar area charts. It represents data as a series of points radiating from a central point. Options allow control over the number of points, angles, and labels. Key options include:

Custom Scales

For highly specialized data or visualization needs, you can create custom scales. This involves extending Chart.js’s scale classes and implementing custom methods for determining tick positions, formatting labels, and drawing the scale. This is an advanced technique requiring a thorough understanding of Chart.js’s internal architecture. Refer to Chart.js’s documentation for detailed information on creating custom scales. This generally involves creating a class that extends one of Chart.js’s scale classes and implementing the necessary methods for generating ticks, determining tick positions, and formatting labels.

Plugins and Extensions

Chart.js’s plugin architecture allows for extending its functionality without modifying its core code. Plugins add features like annotations, zooming, data exporting, and much more.

Plugin Architecture

A Chart.js plugin is a JavaScript object with specific methods that hook into different stages of the chart’s lifecycle. The core methods are:

These methods allow plugins to interact with the chart at various stages of its creation and update process. For example, a plugin could add annotations in afterDraw or handle user interactions in afterEvent.

Creating Custom Plugins

To create a custom plugin, define a JavaScript object with the id and the hook methods you need. For instance, a plugin to add a title could look like this:

const myPlugin = {
  id: 'myPlugin',
  beforeDraw: (chart) => {
    const ctx = chart.ctx;
    ctx.fillStyle = 'blue';
    ctx.font = 'bold 16px sans-serif';
    ctx.fillText('My Custom Title', 10, 20);
  }
};

Chart.register(myPlugin);

Register your plugin using Chart.register(myPlugin) before creating your chart instance.

Using Pre-built Plugins

Many pre-built plugins are available on the internet and via npm. These plugins typically provide ready-to-use features. To use a pre-built plugin:

  1. Install: Install the plugin using npm (or yarn).
  2. Import: Import the plugin into your JavaScript file.
  3. Register: Register the plugin with Chart.js using Chart.register(plugin).
  4. Configure: Configure the plugin’s options within the chart’s options.plugins object. The specific configuration will vary depending on the plugin.

Common Plugins

Some common categories of plugins include:

Before using any third-party plugin, carefully review its documentation to understand its usage, configuration options, and any potential dependencies.

Accessibility

Chart.js itself doesn’t inherently provide robust accessibility features. Building accessible charts requires careful consideration and often involves supplemental techniques beyond the core library. While Chart.js doesn’t directly support all aspects of accessibility, developers can implement best practices to improve the experience for users with disabilities.

ARIA Attributes

ARIA (Accessible Rich Internet Applications) attributes can be added to the chart’s elements to provide assistive technologies (screen readers) with additional information. This requires interacting with the chart’s underlying DOM elements, which is often challenging because Chart.js generates these dynamically.

Adding ARIA attributes generally requires custom code or plugins that interact with the generated DOM elements after the chart has been rendered.

Keyboard Navigation

Chart.js doesn’t provide built-in keyboard navigation. To enable keyboard navigation, you’ll need to implement custom functionality. This typically involves adding event listeners for keyboard events (e.g., arrow keys, tab) and updating the chart’s state or focus accordingly. This would likely require a custom plugin or significant code additions to handle the keyboard interactions and focus management.

Screen Reader Compatibility

Screen reader compatibility is significantly improved by using ARIA attributes. However, even with appropriate ARIA attributes, screen readers may not always perfectly interpret complex charts.

Creating truly accessible charts with Chart.js requires a multi-faceted approach combining ARIA attributes, appropriate labels, alternative data representations, and consideration for screen reader usage. There’s no single solution, and a thorough understanding of accessibility best practices is needed for successful implementation.

Troubleshooting

This section covers common issues encountered when working with Chart.js and provides strategies for resolving them.

Common Errors

Debugging Tips

Performance Optimization

Browser Compatibility

Chart.js generally supports modern browsers. However, older browsers or those with limited JavaScript support might exhibit issues. Refer to Chart.js’s official documentation for its stated browser compatibility.

Remember to always consult the official Chart.js documentation and online resources for the most up-to-date information on troubleshooting and best practices.

API Reference

This section provides a high-level overview of the Chart.js API. For complete and detailed information, refer to the official Chart.js documentation.

Chart Class

The Chart class is the central object representing a chart instance. It’s created by passing the canvas context and configuration options. Key methods and properties include:

Controller Methods

Controllers manage the rendering and update logic for specific chart types (bar, line, pie, etc.). They are not directly accessed by developers but are essential to Chart.js’s internal workings. Understanding their functionalities, however, helps in understanding how charts behave. Key responsibilities include:

Plugin API

The plugin API is used to extend Chart.js’s functionality. A plugin is an object with methods that hook into the chart’s lifecycle. Key methods were discussed in the Plugins and Extensions section. The options.plugins section in the chart configuration allows controlling plugin options.

Scale API

The scale API provides methods to interact with the chart’s axes (scales). This is done indirectly through the options.scales object. Each scale type (linear, logarithmic, time, etc.) has its own set of configuration options, but common properties include:

Direct access to scale objects is generally through Chart.js internal methods and not typically needed for common customizations.

Element API

Chart.js elements represent the visual components of the chart (bars, points, arcs, etc.). You don’t directly instantiate elements but access them through the Chart instance. Methods like chart.getElementsAtEvent(e) can help retrieve elements at a specific location on the chart. The properties and methods of elements depend on the specific chart type, and direct manipulation is generally not recommended unless you’re creating highly custom chart extensions.

This API reference provides a high-level summary. Always consult the official Chart.js documentation for the most current and detailed API information. The documentation includes detailed explanations of each method, property, and configuration option.