Web Development compare

Chart.js library simplifies adding charts to web applications

The Chart.js library uses the HTML5 Canvas element as the launching pad for a full-featured package for creating and presenting charts.

When it comes to presenting data, the old adage "a picture is worth a thousand words" comes to mind. A nice line graph or pie chart communicates in seconds what it could take an hour to explain with words.

Desktop users have lots of options for working with data and creating charts, such as Microsoft Excel and similar offerings in LibreOffice and OpenOffice.org. Plug-ins are available for web presentations, but those can be problematic when shared beyond a small group. However, technology advancements with HTML5 and JavaScript make a package like Chart.js possible. 

The blank Canvas

Creating charts in the browser has always been necessary, but it has not always a straightforward or consistent process. In the past, technologies like ActiveX or even Flash have been used, but the maturation of web technologies with HTML5, CSS3, and JavaScript make it much more possible within the browser. More specifically, the Canvas feature of HTML5 opens the door for more rich graphic elements in a web page.

Basically, the Canvas element is used to draw graphics on the fly, usually with JavaScript. The actual Canvas element (<canvas>) is the container -- a rectangle area. It has various methods for creating shapes and text and adding images. The following example creates a 300x300 black rectangle with white text.

<!DOCTYPE html>
<html lang="en">
<head>
<title>TechRepublic.com – HTML Canvas example</title>
<script type="text/javascript">
function createCanvas() {
var cvs = document.getElementById('exampleCanvas');
var ctx = cvs.getContext('2d');
ctext.fillStyle = '#000';
ctext.fillRect(0, 0, 300, 300);
ctext.fillStyle = '#fff';
ctext.font = 'bold 20px sans-serif';
ctext.fillText('TechRepublic.com Rules!', 20, 50);
}
</script></head>
<body onload="createCanvas();">
<canvas id="exampleCanvas" width="300" height="300"></canvas>
</body></html>

The Chart.js library uses the Canvas element as the launching pad for a full-featured package for creating and presenting charts on the web.

Choose your chart type

Chart.js is a freely available (fully extensible/customizable) library hosted on GitHub. The full source file is 44kb; the minified version is only 20 kb; and it drops to 4.5k when compressed. It is not dependent on any other library. It utilizes the HTML Canvas element, so browser support is listed on its site as modern browsers; however, older browsers are supported via polyfills, which is downloadable code that provides facilities that are not built into a web browser.

You can customize the Chart.js library to create whatever chart you visualize. The library provides six basic designs by default.

  • Line: Show your data as the peaks and valleys of a line graph.
  • Bar: Demonstrate trends with many different shaped bars.
  • Radar: Present data just like your local meteorologist.
  • Pie: Present data as slices of the overall circle.
  • Polar area: It's easier to quote the documentation on this chart as it is similar to pie charts. The variable isn't the circumference of the segment, but the radius of it.
  • Doughnut: Think of a pie chart that is presented in a doughnut shape. The inner circle or hole in the middle is customizable.

The base of everything is the Chart object, which contains methods for creating and manipulating the chart types. Using the Chart object is a simple process. The following steps provide the basic approach to creating charts using the library.

  1. Include the Chart.js library in the web page.
  2. Create a Canvas element within the web page.
  3. In script, obtain the context of the Canvas element.
  4. Assemble data to be used to fill the Chart.
  5. Create the chart via script -- pass context element to Chart and individual methods to create chart type (data and options passed via method).

The Chart object has methods for each chart type with easy to remember names like Bar, Doughnut, Line, Pie, PolarArea, and Radar -- syntax that cannot be simpler. The one caveat is the data is passed to each of the chart types as an array with the format depending on the type. The following example creates a bar chart showing the downward trend in wins for the Philadelphia Phillies from 2010-2012.

<!DOCTYPE html>
<html lang="en">
<head>
<title>TechRepublic.com Example</title>
<script src="Chart.js"></script>
<script type="text/javascript">
function createChart() {
var data = {
labels: ["Apr", "May", "Jun", "Jul", "Aug", "Sep"],
datasets: [
{
fillColor: "rgba(225,0,0,1)",
strokeColor: "rgba(225,0,0,1)",
data: [12, 16, 13, 15, 18, 21]
},
{
fillColor: "rgba(0,26,225,1)",
strokeColor: "rgba(0,26,225,1)",
data: [18, 16, 17, 17, 18, 16]
},
{
fillColor: "rgba(24,31,28,0.5)",
strokeColor: "rgba(24,31,28,0.5)",
data: [11, 16, 9, 10, 17, 17]
}  ]  }
var cht = document.getElementById('trChart');
var ctx = cht.getContext('2d');
var barChart = new Chart(ctx).Bar(data);
}
</script></head>
<body onload="createChart();">
<canvas id="trChart" width="400" height="400"></canvas>
</body></html>

As the example demonstrates, the bar chart accepts two arrays for the labels and dataset(s). The data has many options (covered in the documentation), but we only use fill color (for actual bars) and the data. Figure A shows the chart loaded in Chrome.

Figure A

Chartjs_FigA_081613.jpg

An example of using the Chart.js bar chart.

The constructor for each chart type accepts a second optional parameter that can be used to specify the various formatting options. These allow you to change characteristics like the scale, colors, font, and so forth.

The next code snippet changes our previous example to use some of the available options to change the presentation. Figure B shows the chart presented using these options.

function createChart() {
var data = {
labels: ["Apr", "May", "Jun", "Jul", "Aug", "Sep"],
datasets: [
{
fillColor: "rgba(225,0,0,1)",
data: [12, 16, 13, 15, 18, 21]
},
{
fillColor: "rgba(0,26,225,1)",
data: [18, 16, 17, 17, 18, 16]
},
{
fillColor: "rgba(24,31,28,0.5)",
data: [11, 16, 9, 10, 17, 17]
} ] }
var options = { 
scaleOverlay: true,
scaleShowGridLines: true,
scaleOverride: true,
scaleSteps: 4,
scaleStepWidth: 5,
scaleStartValue: 0,
scaleLineColor: "rgba(0,0,0,.1)",
scaleLineWidth: 1,
scaleShowLabels: true,
scaleFontSize: 16,
scaleFontColor: "#000",
barDatasetSpacing: 2,
barStrokeWidth: 2
};
var cht = document.getElementById('trChart');
var ctx = cht.getContext('2d');
var barChart = new Chart(ctx).Bar(data, options);
}

Figure B

Chartjs_FigB_081613.jpg

Bar chart with various options utilized.

The Chart.js documentation states it works with modern browsers, but there can be issues with older browsers like Internet Explorer 7 or 8. The documentation provides information on workarounds to support older browsers.

Seeing is believing

I stumbled upon the Chart.js library while searching for a solution to another development challenge, but I kept it in the back of my mind for another project where the client wanted to include charts on their site. It was an intranet solution, so the browser was somewhat controlled, albeit I didn't have to tackle many of the issues with older browsers. The library has performed well and provided everything needed for the project.

Chart.js allows you to quickly create and deliver basic charts. It will be interesting to see if or how the library evolves. For now, the Chart.js library fills a need.

About

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

1 comments
ChloeBoylan
ChloeBoylan

Chart.js is a great library for simple charts. If you ever need something with more functionality or for big data, check out ZingChart. www.zingchart.com