HTML & CSS - - By Monty Shokeen

Fancy, Responsive Charts with Chart.js

Data is all around us. While search engines and other applications work most optimally with text based representation of data, people find data represented visually to be easy to comprehend. Earlier this year, SitePoint published Aurelio’s article presenting an introduction to Chart.js. This tutorial will provide a quick recap of that introduction followed by a deeper look into the features of Chart.js.

Getting Started

Chart.js is an HTML5 canvas based responsive, flexible, light-weight charting library. The library supports six different chart types, each of these chart types coming with a load of customization options. If that is not enough, you also have the ability to create your own custom chart types.

All six core chart types in Chart.js are just 11kb minified and gzip’d and the library is modular so you can further reduce the request size for the file by only including the chart type that you actually need. Below is the cdnjs link to include it:

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

Available Configuration Options

Chart.js allows you to change almost every aspect of your charts — from tool tips to animation. In this section I will modify a few settings to demonstrate what Chart.js is capable of creating. Here is the HTML we’ll start with:

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

For the first demonstration, I will create a line chart. There are some basic options that you need to set for the charts to make sense. The line chart expects an array of labels and datasets. The labels appear on the X axis. I have filled up the line chart with some dummy data. The data is broken up into an array of data sets. Each data set has a color for the fill, the line, and the points.

I have set fillColor to transparent in this case. If you don’t set a value of fillColor it will be set to black or grey instead. Same goes for other values. The colors are defined using RGBA, RGB, hex, or HSL format, similar to CSS.

var lineData = {
  labels: ['Data 1', 'Data 2', 'Data 3', 'Data 4', 
           'Data 5', 'Data 6', 'Data 7'],
  datasets: [{
    fillColor: 'rgba(0,0,0,0)',
    strokeColor: 'rgba(220,180,0,1)',
    pointColor: 'rgba(220,180,0,1)',
    data: [20, 30, 80, 20, 40, 10, 60]
  }, {
    fillColor: 'rgba(0,0,0,0)',
    strokeColor: 'rgba(151,187,205,1)',
    pointColor: 'rgba(151,187,205,1)',
    data: [60, 10, 40, 30, 80, 30, 20]
  }]
}

Setting Global Options

I have included the code that sets some global values. animationSteps determines animation duration. There are many more options that you can modify according to your needs, such as scaleLineColor and scaleIntegersOnly. I suggest that you go through the Chart.js documentation to see what else this library has to offer.

Chart.defaults.global = {
  animationSteps : 50,
  tooltipYPadding : 16,
  tooltipCornerRadius : 0,
  tooltipTitleFontStyle : 'normal',
  tooltipFillColor : 'rgba(0,160,0,0.8)',
  animationEasing : 'easeOutBounce',
  scaleLineColor : 'black',
  scaleFontSize : 16
}

Setting Chart Specific Options

Besides Global options, there are configuration options available for individual chart types. I will set a few of these options in this line chart to give you an idea:

var ctx = document.getElementById('canvas').getContext('2d');
var lineDemo = new Chart(ctx).Line(lineData, {
  responsive: true,
  pointDotRadius: 10,
  bezierCurve: false,
  scaleShowVerticalLines: false,
  scaleGridLineColor: 'black'
});

Charts generated by Chart.js are not responsive by default. Setting responsive to true (as done above) makes them responsive. If you need to make every chart responsive, I recommend that you set this globally instead, like this:

Chart.defaults.global.responsive = true;

Below you can see the demo of the line chart:

See the Pen Chart.js Line Chart Demo by SitePoint (@SitePoint) on CodePen.

Adding and Removing Data Dynamically

Sometimes you need to display data that changes over time. A classic example of this scenario is the stock market. In this section I will create a bar chart and dynamically remove as well as add data to it. I will be using some random data and I have decided to represent data with a bar chart in this case. Most of the code in this example will be similar to the previous example. Once we have our HTML (same as previous example), we can add our JavaScript.

First we will write code to fill up our chart with dummy data. I use a function expression to generate random values and then store it in a variable dData . These values are then used to provide us with random data whenever the need arises. As in the previous example, I create an array of labels and datasets and set an arbitrary fillColor.

var dData = function() {
  return Math.round(Math.random() * 90) + 10;
};

var barData = {
  labels: ['dD 1', 'dD 2', 'dD 3', 'dD 4',
           'dD 5', 'dD 6', 'dD 7', 'dD 8'],
  datasets: [{
    fillColor: 'rgba(0,60,100,1)',
    strokeColor: 'black',
    data: [dData(), dData(), dData(), dData(),
           dData(), dData(), dData(), dData()]
  }]
}

Now it’s time to write the code that removes and adds bars to our chart. I begin by initializing the index variable at a value of 11. I am using two methods: removeData() and addData(valuesArray,label). Calling removeData() on a chart instance removes the first value for all datasets on that particular chart. In case of barChartDemo, the first value of the dataset is removed. Calling addData() passing an array of values along with labels adds a new data point at the end of the chart. The code snippet below updates the chart every 3 seconds.

var index = 11;
var ctx = document.getElementById('canvas').getContext('2d');
var barDemo = new Chart(ctx).Bar(barData, {
  responsive: true
});

setInterval(function() {
  barDemo.removeData();
  barDemo.addData([dData()], 'dD ' + index);
  index++;
}, 3000);

An alternative method to update values in a chart is to set the values directly. In the example below, the first line sets the value of the second bar of the first dataset to 60. If you call update at this point, the bar will animate from its current value to 60.

barDemo.datasets[0].bars[2].value = 60;
barDemo.update();

And here is the bar chart demo:

See the Pen Chart.js Responsive Bar Chart Demo by SitePoint (@SitePoint) on CodePen.

Conclusion

This tutorial covered some important features of Chart.js. The first example demonstrated the use of a few global settings. However, Chart.js also provides customization options specific for a chart type. The library allows you to create your own chart types if charts already available don’t meet your requirements. I recommend you to go through the documentation so you can gain a good grasp of what you can and cannot do with this library.

Sponsors
Login or Create Account to Comment
Login Create Account