<

Chart.js - An Introduction

Published on
13,836 Points
3,936 Views
4 Endorsements
Last Modified:
Approved
Rob
I'm an enthusiastic Web Solutions Provider that designs and creates a website YOU want for you and your customers

Introduction

Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this tutorial, I have to assume that you understand basic statistics and how to interpret the data shown in the charts outlined by this tutorial. Chart.js offers the following types of Charts: Line, Bar, Radar, Polar Area, Pie and Doughnut. It is possible to create your own types of charts but one step at a time. These are the types we'll be working with in this tutorial.
 

So what do you need to do to get started?

Bookmark the documentation! http://www.chartjs.org/docs/

Either use a Content Delivery Network (CDN) OR Download the ZIP package and include it with the other files of your website.

I personally recommend to use a CDN via this script tag (version 1.0.2)

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

Open in new window

If you want to have the Chart.js files on your server, download the ZIP from https://github.com/nnnick/Chart.js("Download Zip" found on the right of the page or click this link https://github.com/nnnick/Chart.js/archive/master.zip (may be subject to change) Download.JPGExtract all the files from the ZIP, however the ONLY file needed is the Chart.min.js, and include it in the relative section of your site: 

<script src="/relative/path/to/Chart.min.js"></script>

Open in new window


Add jQuery

While we're at it, let's add jQuery to your page:

<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>

Open in new window

So now your page should look like this

<!DOCTYPE html>
<html>
 <head>
   <meta charset="utf-8">
   <title>My first Chart</title>
   <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
   <script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
 </head>
<body>
</body>
</html>

Open in new window

Nothing flash yet… so what's next?
 

Required Markup (HTML code)

Chart.js makes use of the HTML5 [canvas] element. This is added to the [canvas] section of the page:

<canvas id="myChart" width="400" height="400"></canvas>

Open in new window

We've now got something to work with so let's turn to the JavaScript
 

Now the JavaScript to create a Chart!

To make it easy, I've wrapped up the Chart initialization such that you just need to call the getChart() function to get started. It gets what's needed from the [canvas] element and returns the Chart object that's the basis for creating the charts.

function getChart() {
 var ctx = $("#myChart")[0].getContext("2d");
 return  new Chart(ctx);
}

Open in new window

Then to create a Line chart it's as easy as:

getChart().Line(data, options);

Open in new window

And it's the same for the other charts:

getChart().Bar(data, options);
getChart().Radar(data, options);
getChart().PolarArea(data, options);
getChart().Pie(data, options);
getChart().Doughnut(data, options);

Open in new window

NOTE: It's important that these functions cannot be called unless the page has completely loaded first so either put these either in a [script] tag at the bottom of the page (just before the close []/body] element) OR in jQuery's initialization routine $(function() {...}); and include that in another [script] tag either last in the [head] (after the other [script] tags) or just before the []/body] tag. Now our page looks like this:

<!DOCTYPE html>
<html>
 <head>
   <meta charset="utf-8">
   <title>My first Chart</title>
   <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
   <script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
   <script>
    function getChart() {
    var ctx = $("#myChart")[0].getContext("2d");
return  new Chart(ctx);
}
   </script>
   <script>
       $(function() {
getChart().Line(data, options);
    }
   </script>
 </head>
<body>
    <canvas id="myChart" width="400" height="400"></canvas>
</body>
</html>

Open in new window

NOTE: This will NOT work until we define the two variables data and options! These variables are JavaScript objects (JSON) that give meaning to your chart. The next two sections describe these in more detail.
 

Data Structure (e.g. getChart().Line(data, options))

The data required for each type of graph structure for each is fairly similar. Line and Radar graphs are identical, whilst Bar graphs only differ by not having properties for data points. For Line, Radar and Bar graphs, there are two properties that make up the data structure: labels and datasets

  • The labels are a set of strings that represent the labels on your x-axis.
  • The datasets property is an array and describes the data series of your chart (in other words the values that make up your graph). For Bar and Line graphs this may only be one element in the array but it still needs to be defined as an array.
    • Each dataset has properties to adjust the fill, stroke and point color (see CSS / HTML Color Reference for the available values to use)
    • The two important ones are the label and data properties as they define the name and the values for this series respectively. Each value in the data property array corresponds with the same element in the labels array (not the dataset label but the data labels). They are matched up in the order that they appear so in the example below, to skip a month you would need to add a zero for that month. If there are more values than months, the additional values are ignored.

NOTE: It's worth making the point here that this data does not have to be hard-coded in the webpage (that I've done here for simplicity) but could be requested from a database on your server via AJAX (Asynchronous JavaScript and XML). Assuming your server returned data in JSON in the same layout as described here, you would easily be able to apply it to your graphs. This is outside the scope of this tutorial but you should be aware of that capability.

For example, the data below describes two lines on a chart that have values for each month, and superimposes one over the other.
var data = {
   labels: ["January", "February", "March", "April", "May", "June", "July"],
   datasets: [
       {
           label: "My First dataset",
           fillColor: "rgba(220,220,220,0.2)",
           strokeColor: "rgba(220,220,220,1)",
           pointColor: "rgba(220,220,220,1)",
           pointStrokeColor: "#fff",
           pointHighlightFill: "#fff",
           pointHighlightStroke: "rgba(220,220,220,1)",
           data: [65, 59, 80, 81, 56, 55, 40]
       },
       {
           label: "My Second dataset",
           fillColor: "rgba(151,187,205,0.2)",
           strokeColor: "rgba(151,187,205,1)",
           pointColor: "rgba(151,187,205,1)",
           pointStrokeColor: "#fff",
           pointHighlightFill: "#fff",
           pointHighlightStroke: "rgba(151,187,205,1)",
           data: [28, 48, 40, 19, 86, 27, 90]
       }
   ]
};

Open in new window

For Polar Area, Pie and Doughnut, the data structure is simply an array. Each element in this array is a JavaScript object (JSON) with properties value, color, highlight, label that describe each value.

For example, you can have a chart that has three values superimposed over each other in either the Polar Area, Pie or Doughnut chart type.
var data = [
   {
       value: 300,
       color:"#F7464A",
       highlight: "#FF5A5E",
       label: "Red"
   },
   {
       value: 50,
       color: "#46BFBD",
       highlight: "#5AD3D1",
       label: "Green"
   },
   {
       value: 100,
       color: "#FDB45C",
       highlight: "#FFC870",
       label: "Yellow"
   }
];

Open in new window


NOTE: You pass this data variable to the chart type function: e.g. getChart().Line(data, options);
 

Graph Options (e.g. getChart().Line(data, options))

These are unique to each type of graph. For the most part the default values should suffice. It would pay to look through each of the properties available in order to determine if you need to tweak these values to suit your application. I'll cover some of the more applicable ones for each graph type.
 

Global

These are set differently to the individual chart options. To change the global options you set them by Chart.defaults.global.[option-name]. e.g. Chart.defaults.global.animation = false;

  • animation: (true / false) Whether or not to animate the graph when it is created. This is a personal preference but may be annoying to your users if they change the type of graph or some of the values
  • responsive: (true / false) This is critical if you want the graph to fill its parent HTML element when the user views the graph on different devices. Essentially sets the canvas width to 100% and will scale to fill the as much area as you've allowed for.
 

Line


  • bezierCurve: (true / false) Defaults to true and will give you a curve between points.  Make this false to have a traditional straight line graph
  • pointDot: (true / false) Defaults to true and will show a dot for each data point. Make this false to turn them off
  • datasetFill: (true / false) Defaults to true and will shade underneath the line.
 

Radar


  • pointDot: As with the Line chart this defaults to true so set to false to turn the dots off
As for the other types, the defaults should be fine for most applications.

NOTE: You pass this options variable to the chart type function: e.g. getChart().Line(data, options);

Chart Legends

On all Chart types there is a common legendTemplate property that will generate a legend for your Chart based on the data supplied. The Bar, Line and Radar charts share the same format, whilst the Polar Area, Pie and Doughnut Charts share a slightly different format. By using this property, the Chart object will give you a HTML unordered list of the labels used in your data. They will be colored as per the properties you've set when you created the chart. This is the advantage of using this property, rather than creating it yourself. A simple implementation would be to create two standard templates as each use different datasets when being created:

  • Bar, Line and Radar Charts (see tmp1 below)
  • Polar Area, Pie and Doughnut Charts (see tmp2 below)
This template will loop through the Chart's datasets property looking for strokeColor and label. If they're found they will be inserted and the HTML returned.
var tmp1 = "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"><%if(datasets[i].label){%><%=datasets[i].label%><%}%></span></li><%}%></ul>";

var tmp2 = "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"><%if(segments[i].label){%><%=segments[i].label%><%}%></span></li><%}%></ul>";

Open in new window


When creating the Chart, pass the template like so, depending on the template required:
// for Bar, Line and Radar charts
var options = { legendTemplate: tmp1 };
var mychart = getChart().Line(data, );
---------------------------------------
// for Polar Area, Pie and Doughnut charts
var options = { legendTemplate: tmp2 };
var mychart = getChart().Pie(data, options);

Open in new window

Then to make the template show, add a [div] element to your page where you'd like it to appear:

<div id="chartLegend"></div>

Open in new window

Then when you create the chart, you also set the legend like this:

$("#chartLegend").html(mychart.generateLegend());

Open in new window

How you style the legend is up to you. In the examples, it creates an unordered list so the following style is useful for making a basic, user-friendly legend:

#chartLegend ul {
  list-style: none;
}
#chartLegend li {
  float: left;
  margin-right: 10px;
  min-height: 35px;
}
#chartLegend li > span {
    padding: 5px;
}

Open in new window


Examples


A Line Chart example

 Line.JPG
<!DOCTYPE html>
<html>
 <head>
   <meta charset="utf-8">
   <title>My first Chart</title>
   <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
   <script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
   <style>
    #chartLegend ul {
  list-style: none;
}
#chartLegend li {
  float: left;
  margin-right: 10px;
  min-height: 35px;
}
#chartLegend li > span {
    padding: 5px;
}
</style>
<script>
function getChart() {
        var ctx = $("#myChart")[0].getContext("2d");
return  new Chart(ctx);
}
   </script>
   <script>
       $(function() {
// Set some Chart defaults
Chart.defaults.global.animation = false;

// define the data for the Line Chart
var data = {
   labels: ["January", "February", "March", "April", "May", "June", "July"],
   datasets: [
       {
           label: "My First dataset",
           fillColor: "rgba(220,220,220,0.2)",
           strokeColor: "rgba(220,220,220,1)",
           pointColor: "rgba(220,220,220,1)",
           pointStrokeColor: "#fff",
           pointHighlightFill: "#fff",
           pointHighlightStroke: "rgba(220,220,220,1)",
           data: [65, 59, 80, 81, 56, 55, 40]
       },
       {
           label: "My Second dataset",
           fillColor: "rgba(151,187,205,0.2)",
           strokeColor: "rgba(151,187,205,1)",
           pointColor: "rgba(151,187,205,1)",
           pointStrokeColor: "#fff",
           pointHighlightFill: "#fff",
           pointHighlightStroke: "rgba(151,187,205,1)",
           data: [28, 48, 40, 19, 86, 27, 90]
       }
   ]
};
var tmp1 = "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"><%if(datasets[i].label){%><%=datasets[i].label%><%}%></span></li><%}%></ul>";

// define some options to have sharp straight lines (not curve at the data points)
var options = {
    bezierCurve:false,
    legendTemplate: tmp1
};

// Create the Line Chart
var mychart = getChart().Line(data, options);
$("#chartLegend").html(mychart.generateLegend());
    });
   </script>
 </head>
<body>
    <canvas id="myChart" width="400" height="400"></canvas>
<div id="chartLegend"></div>
</body>
</html>

Open in new window


A Pie Chart example

Pie.JPG
<!DOCTYPE html>
<html>
 <head>
   <meta charset="utf-8">
   <title>My first Chart</title>
   <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
   <script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
   <style>
    #chartLegend ul {
  list-style: none;
}
#chartLegend li {
  float: left;
  margin-right: 10px;
  min-height: 35px;
}
#chartLegend li > span {
    padding: 5px;
}
</style>   
<script>
function getChart() {
        var ctx = $("#myChart")[0].getContext("2d");
return  new Chart(ctx);
}
   </script>
   <script>
       $(function() {
// Set some Chart defaults
Chart.defaults.global.animation = false;

// define the data for the Pie Chart
var data = [
   {
       value: 300,
       color:"#F7464A",
       highlight: "#FF5A5E",
       label: "Red"
   },
   {
       value: 50,
       color: "#46BFBD",
       highlight: "#5AD3D1",
       label: "Green"
   },
   {
       value: 100,
       color: "#FDB45C",
       highlight: "#FFC870",
       label: "Yellow"
   }
];

var tmp2 = "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"><%if(segments[i].label){%><%=segments[i].label%><%}%></span></li><%}%></ul>";


// define some options to have sharp straight lines (not curve at the data points)
var options = {
    legendTemplate: tmp2
};

// Create the Line Chart
    var mychart = getChart().Pie(data, options);
$("#chartLegend").html(mychart.generateLegend());
    });
   </script>
 </head>
<body>
    <canvas id="myChart" width="400" height="400"></canvas>
    <div id="chartLegend"></div>
</body>
</html>

Open in new window


Summary

Where you go from here is up to you. This tutorial will get you started in creating and displaying charts on your site. I encourage you to draw on this article and ask questions on the EE site as you need to in applying what you've learnt here, in building your web application.
4
Comment
Author:Rob
0 Comments

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Join & Write a Comment

Viewers will get an overview of the benefits and risks of using Bitcoin to accept payments. What Bitcoin is: Legality: Risks: Benefits: Which businesses are best suited?: Other things you should know: How to get started:
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
Suggested Courses
Course of the Month15 days, 18 hours left to enroll

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month