An Introduction to Chart.js 2.0 — Six Simple Examples

This article is included in our anthology, Modern JavaScript. If you want everything in one place to get up to speed on modern JavaScript, sign up for SitePoint Premium and download yourself a copy.

This article was peer reviewed by Tim Severien and Simon Codrington. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

If your website is data-intensive, then you will need to find a way to make that data easy to visualize. Humans, after all, are not wonderful at understanding long lists of raw numbers. That’s where charts and graphs come in — they can make complicated statistical relationships obvious and intuitive, as well as more accessibile to non-English speakers. Everyone understands basic charts at the same speed, the same can’t be said for paragraphs rife with technical jargon. Using charts when it’s beneficial, will make your website easier to understand and visually more appealing.

--ADVERTISEMENT--

In this article I’ll introduce you to a JavaScript charting library called Chart.js. Using six stylish examples, I’ll demonstrate how you can use Chart.js to visualize data on your website, as well as configure it to meet your needs.

Why Chart.js?

I chose Chart.js because it can be learned and leveraged quickly. It’s designed with simplicity in mind, yet is extremely customizable. In my experience, charting libraries fall onto a spectrum of complexity, where more complex libraries offer deeper customization, but have steeper learning curves. Chart.js is one of the quickest and easiest libraries to learn that doesn’t heavily limit your options. It comes with eight different chart types that will cover almost all of your data visualization needs.

Chart.js is actively maintained to a high standard by the open source community. It recently reached version 2.0, which came with a few fundamental syntax changes to make code more consistent, as well as offer mobile support. In this article, I’m going to use Chart.js 2.0 and it’s updated syntax. At the end of this article, after giving you a chance to see how Chart.js 2.0 works, there is a section covering the 1.0 -> 2.0 transition and what to expect when reading old Chart.js examples online.

Installing Chart.js

Again, Chart.js is focused on being easy. Easy to learn, easy to leverage, and easy to install. If you’d like to dive into the actual code, check out the GitHub project.

You only need two things to use Chart.js.

1) The library – for this guide, I recommend using a CDN because it’s the easiest way to get up and running fast.

If this code looks intense, don’t worry! All Chart.js examples follow the above format for the most part, so you only have to learn it once. Lets go line by line to understand what’s happening.

var ctx = document.getElementById("myChart").getContext('2d');

This line gets a reference to the <canvas> element we created earlier, then calls the getContext method on it. The getContext method returns an object that provides methods and properties for drawing on the canvas. We store this in a variable named ctx.

Here we are creating the chart object. I’ve excluded the data for a moment to focus on the type property, which determines the type of chart we want. Chart.js’ new Chart() constructor takes two parameters:

Either a reference to a </canvas><canvas> element that the chart will be rendered on, or a reference to its 2d drawing context (here we are using the 2d context). Regardless of which you use, the Chart.js convention is to call it ctx.

An object literal containing the data and the configuration options that Chart.js will use to build your chart. The required properties are type and data. In our example type is ‘line’ because we want a line chart. data is the data you used to populate the chart.

Chart.js uses array location to determine graph position, so the first point of ‘apples’ will have the value ’12’, the second will have ’19’, and so on. Adding new lines is as easy as adding a new object with a label and data.

Finally, I have set an rgba background color for each data set to make it more visually appealing.

Radar Charts

Radar charts are my favorite type, and again they are in the same family as line and bar charts. Radar charts are just line charts with a radial X axis opposed to a straight line. To get a quick radar chart, change:

type: 'bar'

to:

type: 'radar'

Because that’s just how Chart.js rolls.

Unfortunately, the result is a bit ugly and very hard to read. Bar charts don’t have overlap, so solid colors are beneficial. This is not the case with radar charts, which do leverage overlap. We can accommodate this by updating the opactity value of our backgroundColor and adding a borderColor.

As usual, specifying that this is a polar chart can be done with a single line. Change:

type: 'radar'

to:

type: 'polarArea'

But, the polar area is the first chart I’ve covered that can’t be used to compare two data sets. The previous examples were different ways of contrasting two arrays of equal length, whereas the polar chart (and pie chart, which will be covered next) only visualize a single group of numbers.

Pie & Doughnut Charts

You can probably guess this part by now. Change:

type: 'polarArea'

to:

type: 'pie'

The type property is the key to Chart.js. Remember how easy it was to transition from a line chart to bar and radar chart? Well, polar, pie, and doughnut charts are equally interchangeable. With that single change, we can alternate from a polar chart to a pie chart.

Doughnut charts have an interesting property called cutoutPercentage that dictates how big the center hole is. To dive into that, I first need to show you something about Chart.js I’ve ignored to help you speed through the basic chart types.

Now that you’re familiar with the fundamentals of Chart.js, it’s time to cover some of the tricks availible with options.

Titles

It’s easy to add a title to any Chart.js chart by adding this set of options. Native titles are awesome, but it’s worth noting that they are mostly static and unchanging. This will matter when we try to add custom events in a minute.

options: {
title: {
display: true,
text: 'Custom Chart Title'
}
}

The doughnut hole

The cutoutPercentage property is a value from 0 to 50. Pie charts are just doughnut charts with a cutoutPercentage of 0.

options: {
cutoutPercentage: 10,
}

Stacking bar charts

If you would prefer that your bar charts were stacked, just add the following set of options into your bar chart code:

options: {
scales: {
yAxes: [{
stacked: true
}]
}
}

Each chart type has plenty of options for you to dig through. I encourage you to do so.

Handling Events

As mentioned previously clicking on a legend will toggle the data set associated with that particular legend. Let’s augment that with our own functionality:

This code saves a reference to the legend item’s onClick function into a variable called original . It then overwrites this function with our own customized version. The e parameter that we are passing to it is a reference to the click event that caused the function to fire and the legendItem parameter is a reference to the legend that was clicked on. Once we’re done adding our own code, we call the original function specifying a this value and passing through the parameters it is expecting. This results in the default action for clicking on a legend (toggling the data set) being carried out.

In other words, We can now package any functionality we want on top of the onClick() call as long as we put it above original.call().

A Concrete Example

Let’s augment our previous code so that when a user clicks on a legend, the caption at the bottom of the chart updates automatically.

We are only changing the caption, but you can add any functionality you want. For example, a dashboard might have columns of the daily apples and oranges values. The dashboard could also dynamically update based on the status of your chart with the power of a custom callback. Creating interactive data is easy with Chart.js.

As you can see, we’re using an object literal to keep track of the status of the legends. We’re also taking advantage of the legend.text and legend.hidden properties to update its state. The filter function will return any of the object keys whose value is true which we use to build our caption.

Version 1.0 focuses on using function chaining to create a specific type of chart, and then passing in data and options. Version 2.0 switches this up by letting the user create a generic chart object and then pass in type as well as data and options. The second approach matches up more with the philosophy of Chart.js by being as modular and individual as possible. It’s worth noting Chart.js 2.0 is backwards compatible and still accepts 1.0 syntax.

Another key feature of Chart.js 2.0 is mobile support. Charts can now scale to fit mobile screens and handle touch events on mobile browsers. With the current proliferation of mobile devices, this is a must-have feature for websites in 2016.

Another feature new to 2.0 that we used in this guide is title. Charts now have integrated titles that will cooperate with the chart they’re attached to.

Conclusion

Chart.js is a perfect match for rapid prototyping of simple charts. There are eight main chart types, of which we have covered: line, bar, radar, polarArea, pie and doughnut. These diverse charts cover most common ways to visualize data, meaning that Chart.js is probably the only graphing library you’ll need for your next project.

If you want to learn more about Chart.js, I highly recommend the docs, which you can find on the Chart.js website. If you have any questions or comments, I’d love to hear them below.