Tuesday, September 6, 2016

An Introduction to Chart.js 2.0 — Six Simple Examples

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="http://ift.tt/2c5hbLq"></script>

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

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

Alternatively, you can use a package managers 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. A reference to a <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 dataset 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 graph 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]
    }]
  }
});

Continue reading %An Introduction to Chart.js 2.0 — Six Simple Examples%


by Jack Rometty via SitePoint

No comments:

Post a Comment