An Introduction to Chart.js 2.0 — Six Simple Examples

Jack Rometty
Share

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.

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.

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.min.js"></script>

2) A <canvas> element, as Chart.js leverages HTML5 canvas.

</canvas><canvas id="myChart"></canvas>

Alternatively, you can use a package manager to download the library. For more information, see the Getting Started guide.

Simple, eh? Now without further ado, let’s look at what Chart.js has to offer.

Line Chart

This is all you need to create a minimum line chart in Chart.js. Just put it inside of a <script></script> somewhere in your <body> after you declare the HTML5 canvas.

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
    datasets: [{
      label: 'apples',
      data: [12, 19, 3, 17, 6, 3, 7],
      backgroundColor: "rgba(153,255,51,0.4)"
    }, {
      label: 'oranges',
      data: [2, 29, 5, 5, 2, 3, 10],
      backgroundColor: "rgba(255,153,0,0.4)"
    }]
  }
});

See the Pen 2 – Line chart by SitePoint (@SitePoint) on CodePen.

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.

var myChart = new Chart(ctx, {
  type: 'line',
  data: // array of line data goes here
});

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:

  1. 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.
  2. 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.

To learn more about line charts with Chart.js, check out the docs

Pro tip: clicking on any of the legends for the charts (“Apples” and “Oranges” here) will toggle that particular data set. This works for all chart types.

Bar Chart

Bar charts are (mostly) just line charts that look a bit different. By changing one line of our previous example, we can create a bar chart.

type: 'line'

to:

type: 'bar'

Yes, it’s really that easy.

See the Pen 2. Bar Chart by SitePoint (@SitePoint) on CodePen.

The full documentation on bar charts can be found here.

Here’s the full code for this example:

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["M", "T", "W", "R", "F", "S", "S"],
    datasets: [{
      label: 'apples',
      data: [12, 19, 3, 17, 28, 24, 7]
    }, {
      label: 'oranges',
      data: [30, 29, 5, 5, 20, 3, 10]
    }]
  }
});

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.

{
  label: 'apples',
  backgroundColor: "rgba(179,11,198,.2)",
  borderColor: "rgba(179,11,198,1)",
  data: [12, 19, 3, 17, 6, 3, 7]
}

This adds a clearish background and lets us visualize the overlap.

See the Pen 3. Radar Charts by SitePoint (@SitePoint) on CodePen.

To read more about radar charts, check out the docs.

Here’s the full code from this example:

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'radar',
  data: {
    labels: ["M", "T", "W", "T", "F", "S", "S"],
    datasets: [{
      label: 'apples',
      backgroundColor: "rgba(153,255,51,0.4)",
      borderColor: "rgba(153,255,51,1)",
      data: [12, 19, 3, 17, 28, 24, 7]
    }, {
      label: 'oranges',
      backgroundColor: "rgba(255,153,0,0.4)",
      borderColor: "rgba(255,153,0,1)",
      data: [30, 29, 5, 5, 20, 3, 10]
    }]
  }
});

Polar Charts

Polar charts give each data point an equal amount of radial space. Segments with larger values extend further from the center of the graph. Here’s the polar chart for our apples data set.

See the Pen 4. Polar Charts by SitePoint (@SitePoint) on CodePen.

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.

Here’s the full code for this example:

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
  type: 'polarArea',
  data: {
    labels: ["M", "T", "W", "T", "F", "S", "S"],
    datasets: [{
      backgroundColor: [
        "#2ecc71",
        "#3498db",
        "#95a5a6",
        "#9b59b6",
        "#f1c40f",
        "#e74c3c",
        "#34495e"
      ],
      data: [12, 19, 3, 17, 28, 24, 7]
    }]
  }
});

The only new code is a backgroundColor array. Each color matches with the data element of the same index.

To read more about polar area charts, check out the docs.

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.

See the Pen 5. Pie Chart by SitePoint (@SitePoint) on CodePen.

And for a Doughnut chart:

type: 'pie'

to:

type: 'doughnut'

See the Pen 6. Doughnut Chart by SitePoint (@SitePoint) on CodePen.

To read more about pie and doughnut charts, check out the docs.

Here’s the full code for the pie chart:

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
  type: 'pie',
  data: {
    labels: ["M", "T", "W", "T", "F", "S", "S"],
    datasets: [{
      backgroundColor: [
        "#2ecc71",
        "#3498db",
        "#95a5a6",
        "#9b59b6",
        "#f1c40f",
        "#e74c3c",
        "#34495e"
      ],
      data: [12, 19, 3, 17, 28, 24, 7]
    }]
  }
});

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.

Configuring Chart.js

In every example so far, we’ve used the format:

var myChart = new Chart(ctx, {
  type: //chart type,
  data: // chart data
});

But there’s a third property called options. It fits in right below data.

var myChart = new Chart(ctx, {
  type: //chart type,
  data: // chart data,
  options: // chart options
});

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:

var original = Chart.defaults.global.legend.onClick;
Chart.defaults.global.legend.onClick = function(e, legendItem) {
  // Insert your custom functionality here

  original.call(this, e, legendItem);
};

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.

Here’s the code

var labels = {
  "apples": true,
  "oranges": true
};

var caption = document.getElementById("caption");

var update_caption = function(legend) {
  labels[legend.text] = legend.hidden;

  var selected = Object.keys(labels).filter(function(key) {
    return labels[key];
  });

  var text = selected.length ? selected.join(" & ") : "nothing";

  caption.innerHTML = "The above chart displays " + text;
};

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.

See the Pen 7. Bar Chart with Custom onClick() by SitePoint (@SitePoint) on CodePen.

Chart.js 2.0 vs 1.0

This article has used Chart.js 2.0 syntax. Chart.js 2.0 is relatively new to 2016. The most obvious difference between 2.0 and 1.0 being how to declare charts.

1.0

var LineChartDemo = new Chart(ctx).Line(
    //data here,
    //options here
);

2.0

var myChart = new Chart(ctx, {
    type: 'line',
    data: //data here,
    options: //options here
}

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.

The full list of updates can be found in the 2.0.0 release notes.

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.