Fancy, Responsive Charts with Chart.js

Share this article

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.

Frequently Asked Questions (FAQs) about Fancy Responsive Charts with Chart.js

How can I make my Chart.js chart fully responsive?

Making your Chart.js chart fully responsive involves setting the responsive configuration option to true. This allows the chart to resize itself when the window size changes. You can do this by adding the following code to your chart configuration:

var myChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
responsive: true
}
});
This code will ensure that your chart adjusts its size whenever the window size changes, ensuring a fully responsive design.

Why is my Chart.js chart not resizing correctly?

If your Chart.js chart is not resizing correctly, it could be due to a few reasons. One common issue is that the canvas element containing the chart is not being resized correctly. Ensure that the canvas element has a relative position and a width and height of 100%. Another issue could be that the responsive option in the chart configuration is not set to true. Check your chart configuration to ensure that the responsive option is set correctly.

How can I customize the appearance of my Chart.js chart?

Chart.js provides a wide range of options for customizing the appearance of your charts. You can customize the colors, labels, tooltips, and much more. For example, to customize the color of the bars in a bar chart, you can use the following code:

var myChart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
backgroundColor: 'rgba(75, 192, 192, 0.2)'
}]
}
});
This code will set the background color of the bars to a light blue color. You can customize many other aspects of the chart’s appearance using similar options.

How can I add tooltips to my Chart.js chart?

Tooltips in Chart.js are enabled by default and will appear when you hover over data points on the chart. You can customize the appearance and behavior of tooltips using the tooltips configuration option. For example, to change the background color of tooltips, you can use the following code:

var myChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
tooltips: {
backgroundColor: 'rgba(0, 0, 0, 0.8)'
}
}
});
This code will set the background color of tooltips to a semi-transparent black color. You can customize many other aspects of tooltips using similar options.

How can I add animations to my Chart.js chart?

Chart.js provides a variety of options for adding animations to your charts. You can control the duration, easing function, and other aspects of animations using the animation configuration option. For example, to animate the chart with a duration of 2000 milliseconds and an easing function of ‘easeOutBounce’, you can use the following code:

var myChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
animation: {
duration: 2000,
easing: 'easeOutBounce'
}
}
});
This code will animate the chart with a bouncing effect over a duration of 2 seconds. You can customize many other aspects of animations using similar options.

Monty ShokeenMonty Shokeen
View Author

Monty is a front-end developer who loves to learn about new JavaScript libraries and frameworks. He has been doing front-end development for three years now and likes to write about interesting libraries and tools that he comes across in his research.

bar chartChartsline graphLouisL
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week