JavaScript
Article

Creating Beautiful Charts with Chart.js

By Aurelio De Rosa

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.

Versioning. A slightly sarcastic daily email for discerning web people. Sign up today!

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?

More:
Comments
runjep

Nice article - how can I get the labels listed next to the donut?

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.