Step-by-step guide

Follow this guide to get familiar with all major concepts of Chart.js: chart types and elements, datasets, customization, plugins, components, and tree-shaking. Don’t hesitate to follow the links in the text.

We’ll build a Chart.js data visualization with a couple of charts from scratch:

result

Build a new application with Chart.js

In a new folder, create the package.json file with the following contents:

  1. {
  2. "name": "chartjs-example",
  3. "version": "1.0.0",
  4. "license": "MIT",
  5. "scripts": {
  6. "dev": "parcel src/index.html",
  7. "build": "parcel build src/index.html"
  8. },
  9. "devDependencies": {
  10. "parcel": "^2.6.2"
  11. },
  12. "dependencies": {
  13. "@cubejs-client/core": "^0.31.0",
  14. "chart.js": "^4.0.0"
  15. }
  16. }

Modern front-end applications often use JavaScript module bundlers, so we’ve picked ParcelStep-by-step guide - 图2 (opens new window) as a nice zero-configuration build tool. We’re also installing Chart.js v4 and a JavaScript client for CubeStep-by-step guide - 图3 (opens new window), an open-source API for data apps we’ll use to fetch real-world data (more on that later).

Run npm install, yarn install, or pnpm install to install the dependencies, then create the src folder. Inside that folder, we’ll need a very simple index.html file:

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <title>Chart.js example</title>
  5. </head>
  6. <body>
  7. <!-- <div style="width: 500px;"><canvas id="dimensions"></canvas></div><br/> -->
  8. <div style="width: 800px;"><canvas id="acquisitions"></canvas></div>
  9. <!-- <script type="module" src="dimensions.js"></script> -->
  10. <script type="module" src="acquisitions.js"></script>
  11. </body>
  12. </html>

As you can see, Chart.js requires minimal markup: a canvas tag with an id by which we’ll reference the chart later. By default, Chart.js charts are responsive and take the whole enclosing container. So, we set the width of the div to control chart width.

Lastly, let’s create the src/acquisitions.js file with the following contents:

  1. import Chart from 'chart.js/auto'
  2. (async function() {
  3. const data = [
  4. { year: 2010, count: 10 },
  5. { year: 2011, count: 20 },
  6. { year: 2012, count: 15 },
  7. { year: 2013, count: 25 },
  8. { year: 2014, count: 22 },
  9. { year: 2015, count: 30 },
  10. { year: 2016, count: 28 },
  11. ];
  12. new Chart(
  13. document.getElementById('acquisitions'),
  14. {
  15. type: 'bar',
  16. data: {
  17. labels: data.map(row => row.year),
  18. datasets: [
  19. {
  20. label: 'Acquisitions by year',
  21. data: data.map(row => row.count)
  22. }
  23. ]
  24. }
  25. }
  26. );
  27. })();

Let’s walk through this code:

  • We import Chart, the main Chart.js class, from the special chart.js/auto path. It loads all available Chart.js components (which is very convenient) but disallows tree-shaking. We’ll address that later.
  • We instantiate a new Chart instance and provide two arguments: the canvas element where the chart would be rendered and the options object.
  • We just need to provide a chart type (bar) and provide data which consists of labels (often, numeric or textual descriptions of data points) and an array of datasets (Chart.js supports multiple datasets for most chart types). Each dataset is designated with a label and contains an array of data points.
  • For now, we only have a few entries of dummy data. So, we extract year and count properties to produce the arrays of labels and data points within the only dataset.

Time to run the example with npm run dev, yarn dev, or pnpm dev and navigate to localhost:1234Step-by-step guide - 图4 (opens new window) in your web browser:

result

With just a few lines of code, we’ve got a chart with a lot of features: a legend, grid lines, ticks, and tooltips shown on hover. Refresh the web page a few times to see that the chart is also animated. Try clicking on the “Acquisitions by year” label to see that you’re also able to toggle datasets visibility (especially useful when you have multiple datasets).

Simple customizations

Let’s see how Chart.js charts can be customized. First, let’s turn off the animations so the chart appears instantly. Second, let’s hide the legend and tooltips since we have only one dataset and pretty trivial data.

Replace the new Chart(...); invocation in src/acquisitions.js with the following snippet:

  1. new Chart(
  2. document.getElementById('acquisitions'),
  3. {
  4. type: 'bar',
  5. options: {
  6. animation: false,
  7. plugins: {
  8. legend: {
  9. display: false
  10. },
  11. tooltip: {
  12. enabled: false
  13. }
  14. }
  15. },
  16. data: {
  17. labels: data.map(row => row.year),
  18. datasets: [
  19. {
  20. label: 'Acquisitions by year',
  21. data: data.map(row => row.count)
  22. }
  23. ]
  24. }
  25. }
  26. );

As you can see, we’ve added the options property to the second argument—that’s how you can specify all kinds of customization options for Chart.js. The animation is disabled with a boolean flag provided via animation. Most chart-wide options (e.g., responsiveness or device pixel ratio) are configured like this.

The legend and tooltips are hidden with boolean flags provided under the respective sections in plugins. Note that some of Chart.js features are extracted into plugins: self-contained, separate pieces of code. A few of them are available as a part of Chart.js distributionStep-by-step guide - 图6 (opens new window), other plugins are maintained independently and can be located in the awesome listStep-by-step guide - 图7 (opens new window) of plugins, framework integrations, and additional chart types.

You should be able to see the updated minimalistic chart in your browser.

Real-world data

With hardcoded, limited-size, unrealistic data, it’s hard to show the full potential of Chart.js. Let’s quickly connect to a data API to make our example application closer to a production use case.

Let’s create the src/api.js file with the following contents:

  1. import { CubejsApi } from '@cubejs-client/core';
  2. const apiUrl = 'https://heavy-lansford.gcp-us-central1.cubecloudapp.dev/cubejs-api/v1';
  3. const cubeToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjEwMDAwMDAwMDAsImV4cCI6NTAwMDAwMDAwMH0.OHZOpOBVKr-sCwn8sbZ5UFsqI3uCs6e4omT7P6WVMFw';
  4. const cubeApi = new CubejsApi(cubeToken, { apiUrl });
  5. export async function getAquisitionsByYear() {
  6. const acquisitionsByYearQuery = {
  7. dimensions: [
  8. 'Artworks.yearAcquired',
  9. ],
  10. measures: [
  11. 'Artworks.count'
  12. ],
  13. filters: [ {
  14. member: 'Artworks.yearAcquired',
  15. operator: 'set'
  16. } ],
  17. order: {
  18. 'Artworks.yearAcquired': 'asc'
  19. }
  20. };
  21. const resultSet = await cubeApi.load(acquisitionsByYearQuery);
  22. return resultSet.tablePivot().map(row => ({
  23. year: parseInt(row['Artworks.yearAcquired']),
  24. count: parseInt(row['Artworks.count'])
  25. }));
  26. }
  27. export async function getDimensions() {
  28. const dimensionsQuery = {
  29. dimensions: [
  30. 'Artworks.widthCm',
  31. 'Artworks.heightCm'
  32. ],
  33. measures: [
  34. 'Artworks.count'
  35. ],
  36. filters: [
  37. {
  38. member: 'Artworks.classification',
  39. operator: 'equals',
  40. values: [ 'Painting' ]
  41. },
  42. {
  43. member: 'Artworks.widthCm',
  44. operator: 'set'
  45. },
  46. {
  47. member: 'Artworks.widthCm',
  48. operator: 'lt',
  49. values: [ '500' ]
  50. },
  51. {
  52. member: 'Artworks.heightCm',
  53. operator: 'set'
  54. },
  55. {
  56. member: 'Artworks.heightCm',
  57. operator: 'lt',
  58. values: [ '500' ]
  59. }
  60. ]
  61. };
  62. const resultSet = await cubeApi.load(dimensionsQuery);
  63. return resultSet.tablePivot().map(row => ({
  64. width: parseInt(row['Artworks.widthCm']),
  65. height: parseInt(row['Artworks.heightCm']),
  66. count: parseInt(row['Artworks.count'])
  67. }));
  68. }

Let’s see what’s happening there:

  • We import the JavaScript client library for CubeStep-by-step guide - 图8 (opens new window), an open-source API for data apps, configure it with the API URL (apiUrl) and the authentication token (cubeToken), and finally instantiate the client (cubeApi).
  • Cube API is hosted in Cube CloudStep-by-step guide - 图9 (opens new window) and connected to a database with a public datasetStep-by-step guide - 图10 (opens new window) of ~140,000 records representing all of the artworks in the collection of the Museum of Modern ArtStep-by-step guide - 图11 (opens new window) in New York, USA. Certainly, a more real-world dataset than what we’ve got now.
  • We define a couple of asynchronous functions to fetch data from the API: getAquisitionsByYear and getDimensions. The first one returns the number of artworks by the year of acquisition, the other returns the number of artworks for every width-height pair (we’ll need it for another chart).
  • Let’s take a look at getAquisitionsByYear. First, we create a declarative, JSON-based query in the acquisitionsByYearQuery variable. As you can see, we specify that for every yearAcquired we’d like to get the count of artworks; yearAcquired has to be set (i.e., not undefined); the result set would be sorted by yearAcquired in the ascending order.
  • Second, we fetch the resultSet by calling cubeApi.load and map it to an array of objects with desired year and count properties.

Now, let’s deliver the real-world data to our chart. Please apply a couple of changes to src/acquisitions.js: add an import and replace the definition of the data variable.

  1. import { getAquisitionsByYear } from './api'
  2. // ...
  3. const data = await getAquisitionsByYear();

Done! Now, our chart with real-world data looks like this. Looks like something interesting happened in 1964, 1968, and 2008!

result

We’re done with the bar chart. Let’s try another Chart.js chart type.

Further customizations

Chart.js supports many common chart types.

For instance, Bubble chart allows to display three dimensions of data at the same time: locations on x and y axes represent two dimensions, and the third dimension is represented by the size of the individual bubbles.

To create the chart, stop the already running application, then go to src/index.html, and uncomment the following two lines:

  1. <div style="width: 500px;"><canvas id="dimensions"></canvas></div><br/>
  2. <script type="module" src="dimensions.js"></script>

Then, create the src/dimensions.js file with the following contents:

  1. import Chart from 'chart.js/auto'
  2. import { getDimensions } from './api'
  3. (async function() {
  4. const data = await getDimensions();
  5. new Chart(
  6. document.getElementById('dimensions'),
  7. {
  8. type: 'bubble',
  9. data: {
  10. labels: data.map(x => x.year),
  11. datasets: [
  12. {
  13. label: 'Dimensions',
  14. data: data.map(row => ({
  15. x: row.width,
  16. y: row.height,
  17. r: row.count
  18. }))
  19. }
  20. ]
  21. }
  22. }
  23. );
  24. })();

Probably, everything is pretty straightforward there: we get data from the API and render a new chart with the bubble type, passing three dimensions of data as x, y, and r (radius) properties.

Now, reset caches with rm -rf .parcel-cache and start the application again with npm run dev, yarn dev, or pnpm dev. We can review the new chart now:

result

Well, it doesn’t look pretty.

First of all, the chart is not square. Artworks’ width and height are equally important so we’d like to make the chart width equal to its height as well. By default, Chart.js charts have the aspect ratio of either 1 (for all radial charts, e.g., a doughnut chart) or 2 (for all the rest). Let’s modify the aspect ratio for our chart:

  1. // ...
  2. new Chart(
  3. document.getElementById('dimensions'),
  4. {
  5. type: 'bubble',
  6. options: {
  7. aspectRatio: 1,
  8. },
  9. // ...

Looks much better now:

result

However, it’s still not ideal. The horizontal axis spans from 0 to 500 while the vertical axis spans from 0 to 450. By default, Chart.js automatically adjusts the range (minimum and maximum values) of the axes to the values provided in the dataset, so the chart “fits” your data. Apparently, MoMa collection doesn’t have artworks in the range of 450 to 500 cm in height. Let’s modify the axes configuration for our chart to account for that:

  1. // ...
  2. new Chart(
  3. document.getElementById('dimensions'),
  4. {
  5. type: 'bubble',
  6. options: {
  7. aspectRatio: 1,
  8. scales: {
  9. x: {
  10. max: 500
  11. },
  12. y: {
  13. max: 500
  14. }
  15. }
  16. },
  17. // ...

Great! Behold the updated chart:

result

However, there’s one more nitpick: what are these numbers? It’s not very obvious that the units are centimetres. Let’s apply a custom tick format to both axes to make things clear. We’ll provide a callback function that would be called to format each tick value. Here’s the updated axes configuration:

  1. // ...
  2. new Chart(
  3. document.getElementById('dimensions'),
  4. {
  5. type: 'bubble',
  6. options: {
  7. aspectRatio: 1,
  8. scales: {
  9. x: {
  10. max: 500,
  11. ticks: {
  12. callback: value => `${value / 100} m`
  13. }
  14. },
  15. y: {
  16. max: 500,
  17. ticks: {
  18. callback: value => `${value / 100} m`
  19. }
  20. }
  21. }
  22. },
  23. // ...

Perfect, now we have proper units on both axes:

result

Multiple datasets

Chart.js plots each dataset independently and allows to apply custom styles to them.

Take a look at the chart: there’s a visible “line” of bubbles with equal x and y coordinates representing square artworks. It would be cool to put these bubbles in their own dataset and paint them differently. Also, we can separate “taller” artworks from “wider” ones and paint them differently, too.

Here’s how we can do that. Replace the datasets with the following code:

  1. // ...
  2. datasets: [
  3. {
  4. label: 'width = height',
  5. data: data
  6. .filter(row => row.width === row.height)
  7. .map(row => ({
  8. x: row.width,
  9. y: row.height,
  10. r: row.count
  11. }))
  12. },
  13. {
  14. label: 'width > height',
  15. data: data
  16. .filter(row => row.width > row.height)
  17. .map(row => ({
  18. x: row.width,
  19. y: row.height,
  20. r: row.count
  21. }))
  22. },
  23. {
  24. label: 'width < height',
  25. data: data
  26. .filter(row => row.width < row.height)
  27. .map(row => ({
  28. x: row.width,
  29. y: row.height,
  30. r: row.count
  31. }))
  32. }
  33. ]
  34. // ..

As you can see, we define three datasets with different labels. Each dataset gets its own slice of data extracted with filter. Now they are visually distinct and, as you already know, you can toggle their visibility independently.

result

Here we rely on the default color palette. However, keep in mind every chart type supports a lot of dataset options that you can feel free to customize.

Plugins

Another—and very powerful!—way to customize Chart.js charts is to use plugins. You can find some in the plugin directoryStep-by-step guide - 图18 (opens new window) or create your own, ad-hoc ones. In Chart.js ecosystem, it’s idiomatic and expected to fine tune charts with plugins. For example, you can customize canvas background or add a border to it with simple ad-hoc plugins. Let’s try the latter.

Plugins have an extensive API but, in a nutshell, a plugin is defined as an object with a name and one or more callback functions defined in the extension points. Insert the following snippet before and in place of the new Chart(...); invocation in src/dimensions.js:

  1. // ...
  2. const chartAreaBorder = {
  3. id: 'chartAreaBorder',
  4. beforeDraw(chart, args, options) {
  5. const { ctx, chartArea: { left, top, width, height } } = chart;
  6. ctx.save();
  7. ctx.strokeStyle = options.borderColor;
  8. ctx.lineWidth = options.borderWidth;
  9. ctx.setLineDash(options.borderDash || []);
  10. ctx.lineDashOffset = options.borderDashOffset;
  11. ctx.strokeRect(left, top, width, height);
  12. ctx.restore();
  13. }
  14. };
  15. new Chart(
  16. document.getElementById('dimensions'),
  17. {
  18. type: 'bubble',
  19. plugins: [ chartAreaBorder ],
  20. options: {
  21. plugins: {
  22. chartAreaBorder: {
  23. borderColor: 'red',
  24. borderWidth: 2,
  25. borderDash: [ 5, 5 ],
  26. borderDashOffset: 2,
  27. }
  28. },
  29. aspectRatio: 1,
  30. // ...

As you can see, in this chartAreaBorder plugin, we acquire the canvas context, save its current state, apply styles, draw a rectangular shape around the chart area, and restore the canvas state. We’re also passing the plugin in plugins so it’s only applied to this particular chart. We also pass the plugin options in options.plugins.chartAreaBorder; we could surely hardcode them in the plugin source code but it’s much more reusable this way.

Our bubble chart looks fancier now:

result

Tree-shaking

In production, we strive to ship as little code as possible, so the end users can load our data applications faster and have better experience. For that, we’ll need to apply tree-shakingStep-by-step guide - 图20 (opens new window) which is fancy term for removing unused code from the JavaScript bundle.

Chart.js fully supports tree-shaking with its component design. You can register all Chart.js components at once (which is convenient when you’re prototyping) and get them bundled with your application. Or, you can register only necessary components and get a minimal bundle, much less in size.

Let’s inspect our example application. What’s the bundle size? You can stop the application and run npm run build, or yarn build, or pnpm build. In a few moments, you’ll get something like this:

  1. % yarn build
  2. yarn run v1.22.17
  3. $ parcel build src/index.html
  4. Built in 88ms
  5. dist/index.html 381 B 164ms
  6. dist/index.74a47636.js 265.48 KB 1.25s
  7. dist/index.ba0c2e17.js 881 B 63ms
  8. Done in 0.51s.

We can see that Chart.js and other dependencies were bundled together in a single 265 KB file.

To reduce the bundle size, we’ll need to apply a couple of changes to src/acquisitions.js and src/dimensions.js. First, we’ll need to remove the following import statement from both files: import Chart from 'chart.js/auto'.

Instead, let’s load only necessary components and “register” them with Chart.js using Chart.register(...). Here’s what we need in src/acquisitions.js:

  1. import {
  2. Chart,
  3. Colors,
  4. BarController,
  5. CategoryScale,
  6. LinearScale,
  7. BarElement,
  8. Legend
  9. } from 'chart.js'
  10. Chart.register(
  11. Colors,
  12. BarController,
  13. BarElement,
  14. CategoryScale,
  15. LinearScale,
  16. Legend
  17. );

And here’s the snippet for src/dimensions.js:

  1. import {
  2. Chart,
  3. Colors,
  4. BubbleController,
  5. CategoryScale,
  6. LinearScale,
  7. PointElement,
  8. Legend
  9. } from 'chart.js'
  10. Chart.register(
  11. Colors,
  12. BubbleController,
  13. PointElement,
  14. CategoryScale,
  15. LinearScale,
  16. Legend
  17. );

You can see that, in addition to the Chart class, we’re also loading a controller for the chart type, scales, and other chart elements (e.g., bars or points). You can look all available components up in the documentation.

Alternatively, you can follow Chart.js advice in the console. For example, if you forget to import BarController for your bar chart, you’ll see the following message in the browser console:

  1. Unhandled Promise Rejection: Error: "bar" is not a registered controller.

Remember to carefully check for imports from chart.js/auto when preparing your application for production. It takes only one import like this to effectively disable tree-shaking.

Now, let’s inspect our application once again. Run yarn build and you’ll get something like this:

  1. % yarn build
  2. yarn run v1.22.17
  3. $ parcel build src/index.html
  4. Built in 88ms
  5. dist/index.html 381 B 176ms
  6. dist/index.5888047.js 208.66 KB 1.23s
  7. dist/index.dcb2e865.js 932 B 58ms
  8. Done in 0.51s.

By importing and registering only select components, we’ve removed more than 56 KB of unnecessary code. Given that other dependencies take ~50 KB in the bundle, tree-shaking helps remove ~25% of Chart.js code from the bundle for our example application.

Next steps

Now you’re familiar with all major concepts of Chart.js: chart types and elements, datasets, customization, plugins, components, and tree-shaking.

Feel free to review many examples of charts in the documentation and check the awesome listStep-by-step guide - 图21 (opens new window) of Chart.js plugins and additional chart types as well as framework integrationsStep-by-step guide - 图22 (opens new window) (e.g., React, Vue, Svelte, etc.). Also, don’t hesitate to join Chart.js SlackStep-by-step guide - 图23 (opens new window) and follow Chart.js on TwitterStep-by-step guide - 图24 (opens new window).

Have fun and good luck building with Chart.js!