Creating Beautiful Charts with Chart.js

Share this article

Content is king
. We all have heard or read this sentence that expresses how good text can drive conversion because of the effect on search engines. However, while text is excellent for search engines, sometimes people can better understand a concept by looking at an image or a chart. For example, if your website is specialized about surveys, a description about a survey is important but a chart that summarizes the data of the survey is much more powerful for your users. In this article I’ll introduce you to a JavaScript library called Chart.js that employs the HTML5 canvas element to draw charts on a page. After a brief overview of the library I’ll also show you two examples of use of this library.

What is Chart.js?

Chart.js is a JavaScript library that allows you to draw different types of charts by using the HTML5 canvas element. Since it uses canvas, you have to include a polyfill to support older browsers. The one suggested by the author is ExplorerCanvas, so you may want to stick with it. The library doesn’t have dependencies and its weight is very low as it’s ~11kb in size when minified, concatenated, and served gzipped. However, you’re able to reduce the size even further, if you don’t use all six of the core chart types, by including only the modules you need. So, let’s say that you only need to draw a bar chart in your website, you can include the core and the bar module and save bandwidth for your users. Another cool feature of Chart.js is that the charts are responsive, so they will adapt based on the space available. Finally, unlike many libraries you can find on the web, it provides extensive and clear documentation that makes using its basic features as well as its advanced options very easy. In the next section we’ll see how you can obtain and include it in your website.

Getting Started with Chart.js

The first step to use this library is to download and include it in the page where you plan to draw one or more charts. To download Chart.js you have two possibilities. The first is to download the library by visiting its GitHub repository. A second possibility is to use Bower, the dependency manager for the web, by running the following command:
bower install chartjs --save
Once downloaded, you have to include the JavaScript file(s) in your page. In the next example I’ll assume you want to include the all-inclusive version:
<script src="path/to/Chart.js"></script>
Please note the capital letter of the file. It’s not usual that a library is written with the first letter uppercase so the first time you use it you may struggle in understanding why you obtain a 404 error. Once done, the library will provide all its methods through a global variable named Chart. With the JavaScript file in place we’re ready to create our first chart. To do so you need to instantiate a new Chart
object by passing to it the 2d context of the canvas you want to employ in your page. To understand this concept, let’s say that you have the following element in your page that will be used to place the chart:
<canvas id="skills"></canvas>
If you want to create a pie chart, you have to write the following statements:
var context = document.getElementById('skills').getContext('2d');
var skillsChart = new Chart(context).Pie(data);
where data that isn’t defined in this example, is a variable containing the data to show. Now that you know what it takes to get started with Chart.js, it’s time to see some examples. For the sake of brevity I’ll employ the all-inclusive version of the library in my examples, but you can find all the modules in the “src” folder.

Creating a Pie Chart with Chart.js

In this section I’ll show you how to create a pie chart that shows the skills of a hypothetical developer (I’ll include Java so the developer cannot really be me!). As you might easily guess, the first step is to include the canvas element used to draw the pie chart:
<canvas id="skills" width="300" height="300"></canvas>
Then, we need to create the data used to draw the chart. In a real-world case the data are provided from a server in some way but for now we’ll use a fixed example without the use of a server. For a pie chart we have to pass an array of objects, each of which can contain several properties. However, to be usable and easy to understand at a first glance it should contain for each object the value you want to show, the color of the slice of the pie, and a label as shown below:
var pieData = [
   {
      value: 25,
      label: 'Java',
      color: '#811BD6'
   },
   {
      value: 10,
      label: 'Scala',
      color: '#9CBABA'
   },
   {
      value: 30,
      label: 'PHP',
      color: '#D18177'
   },
   {
      value : 35,
      label: 'HTML',
      color: '#6AE128'
   }
];
Finally, as explained in the previous section, we need to get the 2d context of the canvas and to instantiate the chart:
var context = document.getElementById('skills').getContext('2d');
var skillsChart = new Chart(context).Pie(pieData);
Putting together all the snippets listed in this section result in the following output, also available as a JSfiddle:

Drawing a Bar Chart

The next example we’ll build is a bar chart to show how the number of clients of a hypothetical company have changed in year 2014 compared to year 2010 in some nations. As we’ve done for the previous example we have to place a canvas
element in the page where we want to show the chart:
<canvas id="clients" width="500" height="400"></canvas>
Next, we need to create the data of this fake company:
var barData = {
    labels: ['Italy', 'UK', 'USA', 'Germany', 'France', 'Japan'],
    datasets: [
        {
            label: '2010 customers #',
            fillColor: '#382765',
            data: [2500, 1902, 1041, 610, 1245, 952]
        },
        {
            label: '2014 customers #',
            fillColor: '#7BC225',
            data: [3104, 1689, 1318, 589, 1199, 1436]
        }
    ]
};
As you can see, for a bar chart you have to provide an object containing a property named labels that specifies the names of the instances you want to compare. In our example these instances are Italy, UK, USA, Germany, France, and Japan. In addition, we have to provide a dataset property that defines an array of objects, each of which containing the data we want to compare. In our example we’re comparing the years 2014 and 2010, so we’ll need two objects only. Inside these objects we have to specify a label to give a visual hint of what the data are about, the values for each objects specified as the values of the data property, and optionally the color of the bar. Once done, we are ready to create the chart:
var context = document.getElementById('clients').getContext('2d');
var clientsChart = new Chart(context).Bar(barData);
Putting together all the snippets reported in this section result in the following output, also available as a JSfiddle:

Conclusion

In this article I introduced you to Chart.js, a JavaScript library to create beautiful charts with ease. As you’ve seen the library is very easy, and in this article I showed some examples. Chart.js also provides you several options that I haven’t covered but that you can learn by reading the official documentation. Have you ever used this library? How was your experience? If not, have you used a different one?

Frequently Asked Questions (FAQs) about Creating Beautiful Charts with Chart.js

How can I resolve the “arc is not a registered element” error in Chart.js?

This error typically occurs when you’re trying to use a chart type or feature that isn’t registered in your Chart.js setup. To resolve this, you need to import and register the required chart type or feature. For instance, if you’re using a doughnut chart, you should import and register it as follows:

import { Doughnut } from 'react-chartjs-2';
Chart.register(Doughnut);

How can I customize the colors of my Chart.js charts?

Chart.js provides several options for customizing the colors of your charts. You can specify the color for each dataset in your chart by setting the backgroundColor and borderColor properties in your dataset configuration. For example:

datasets: [{
data: [10, 20, 30],
backgroundColor: ['red', 'blue', 'green'],
borderColor: ['black', 'black', 'black']
}]

How can I add tooltips to my Chart.js charts?

Tooltips in Chart.js are enabled by default and will appear when hovering over points on the chart. You can customize the appearance and behavior of tooltips by modifying the options.tooltips property in your chart configuration. For example, to change the background color of tooltips to white, you would do:

options: {
tooltips: {
backgroundColor: '#fff'
}
}

How can I create a line chart with Chart.js?

Creating a line chart with Chart.js involves specifying type: 'line' in your chart configuration and providing an array of data points. Each data point should be an object with x and y properties representing the coordinates of the point. For example:

type: 'line',
data: {
datasets: [{
data: [{x: 10, y: 20}, {x: 20, y: 40}, {x: 30, y: 60}]
}]
}

How can I add a legend to my Chart.js chart?

Legends in Chart.js are enabled by default and will display the labels of each dataset in your chart. You can customize the appearance and position of the legend by modifying the options.legend property in your chart configuration. For example, to position the legend at the bottom of the chart, you would do:

options: {
legend: {
position: 'bottom'
}
}

How can I create a bar chart with Chart.js?

Creating a bar chart with Chart.js involves specifying type: 'bar' in your chart configuration and providing an array of data points. Each data point should be a number representing the height of the bar. For example:

type: 'bar',
data: {
datasets: [{
data: [10, 20, 30]
}]
}

How can I create a pie chart with Chart.js?

Creating a pie chart with Chart.js involves specifying type: 'pie' in your chart configuration and providing an array of data points. Each data point should be a number representing the size of the pie slice. For example:

type: 'pie',
data: {
datasets: [{
data: [10, 20, 30]
}]
}

How can I create a doughnut chart with Chart.js?

Creating a doughnut chart with Chart.js involves specifying type: 'doughnut' in your chart configuration and providing an array of data points. Each data point should be a number representing the size of the doughnut slice. For example:

type: 'doughnut',
data: {
datasets: [{
data: [10, 20, 30]
}]
}

How can I create a radar chart with Chart.js?

Creating a radar chart with Chart.js involves specifying type: 'radar' in your chart configuration and providing an array of data points. Each data point should be a number representing the value of the radar point. For example:

type: 'radar',
data: {
datasets: [{
data: [10, 20, 30]
}]
}

How can I create a polar area chart with Chart.js?

Creating a polar area chart with Chart.js involves specifying type: 'polarArea' in your chart configuration and providing an array of data points. Each data point should be a number representing the size of the polar area. For example:

type: 'polarArea',
data: {
datasets: [{
data: [10, 20, 30]
}]
}

Aurelio De RosaAurelio De Rosa
View Author

I'm a (full-stack) web and app developer with more than 5 years' experience programming for the web using HTML, CSS, Sass, JavaScript, and PHP. I'm an expert of JavaScript and HTML5 APIs but my interests include web security, accessibility, performance, and SEO. I'm also a regular writer for several networks, speaker, and author of the books jQuery in Action, third edition and Instant jQuery Selectors.

ChartsColinIgitCS
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week