Introduction to Chart.js 2.0 anh Six Simple Examples

View: 343    Dowload: 0   Comment: 0   Post by: hanhga  
Author: none   Category: Javascript   Fields: Other

0 point/0 review File has been tested

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.

Introduction

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 id="myChart"></canvas>

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

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)"
    }]
  }
});

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. ThegetContext 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
});

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'

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]
}

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.

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.

And for a Doughnut chart:

type: 'pie'

to:

type: 'doughnut'

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 acutoutPercentage 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 aboveoriginal.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;
};

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.

Introduction to Chart.js 2.0 anh Six Simple Examples

Introduction to Chart.js 2.0 anh Six Simple Examples Posted on 07-09-2016  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. 5/10 343

Comment:

To comment you must be logged in members.

Files with category

  • JUnit 5 State Of The Union using java

    View: 633    Download: 0   Comment: 0   Author: none  

    JUnit 5 State Of The Union using java

    Category: Javascript
    Fields: Other

    1.5/3 review
    JUnit 5 has been under development for about 14 months now and the prototype is almost a year old. Time to summarize what happened so far, where the project stands, and where it’s going.

  • Getting Started with Dropwizard using java

    View: 736    Download: 0   Comment: 0   Author: none  

    Getting Started with Dropwizard using java

    Category: Javascript
    Fields: Other

    1.5/3 review
    Dropwizard is a framework for building RESTful web services in Java. In this tutorial we’re going to have a look at how to get started with developing a Dropwizard application by building a new service from scratch.

  • Build Query NULL Value in MySql

    View: 340    Download: 0   Comment: 0   Author: none  

    Build Query NULL Value in MySql

    Category: Javascript
    Fields: Other

    2.5/2 review
    Misunderstanding NULL is common mistake beginners do while writing MySql query. While quering in MySql they compare column name with NULL. In MySql NULL is nothing or in simple word it isUnknown Value so if you use comparison operator for NULL values...

  • Manage Your JavaScript Application State with MobX

    View: 406    Download: 0   Comment: 0   Author: none  

    Manage Your JavaScript Application State with MobX

    Category: Javascript
    Fields: Other

    2.25/2 review
    This article was peer reviewed by Michel Weststrate and Aaron Boyer. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

  • Build Bringing Pages to Life with the Web Animations API

    View: 364    Download: 0   Comment: 0   Author: none  

    Build Bringing Pages to Life with the Web Animations API

    Category: Javascript
    Fields: Other

    3/3 review
    This article is by guest author Dudley Storey. SitePoint guest posts aim to bring you engaging content from prominent writers and speakers of the JavaScript community.

  • How to Style Google Custom Search Manually

    View: 346    Download: 0   Comment: 0   Author: none  

    How to Style Google Custom Search Manually

    Category: Javascript
    Fields: Other

    0/0 review
    Website owners very often decide on using Google’s Custom Search Engine (GCSE) for searching through their content instead of using built-in and/or custom search functionality. The reason is simple – it’s much less work, and most often it does the...

  • Test React Components Using Jest

    View: 5116    Download: 0   Comment: 0   Author: none  

    Test React Components Using Jest

    Category: Javascript
    Fields: Other

    4.5/1 review
    This article is by guest author Jack Franklin. SitePoint guest posts aim to bring you engaging content from prominent writers and speakers of the JavaScript community.

  • Programming Question Reverse String without using String function

    View: 821    Download: 0   Comment: 0   Author: none  

    Programming Question Reverse String without using String function

    Category: Javascript
    Fields: Other

    4.5/1 review
    Write a program to reverse string without using string function. You don’t have to use any in-built string library function. This problem can be solved by multiple approaches. Let’s check it.

 

File suggestion for you

File top downloads

logo codetitle
Codetitle.com - library source code to share, download the file to the community
Copyright © 2015. All rights reserved. codetitle.com Develope by Vinagon .Ltd