ChartJS Tutorial For Beginners With PDF

chart js tutorials

Contents

Welcome To The ChartJS Tutorial

This is the starting point to becoming competent with the ChartJS library. Hopefully, around 3 lessons will be released per week from the day this article is published. You can sign up to the newsletter at the end of the article for updates on new lessons too. We will be going through working with the following graphs –

  • Bar
  • Radar
  • Line
  • Donut
  • Pie
  • Scatter
  • Polar Area
  • Area
  • Mixed

chart js charts

Within the series of tutorials, we will see how each can be configured and used in real-life environments. Testing data sourcing from a range of API’s and even some databases. This series will put ChartJS through it’s paces also, delving deep into it’s features, events and styling. By the end of the series, you will feel comfortable enough to construct your very own data visualization dashboards and informative website-graphs.

Managing & Using Data

In general, JavaScript libraries are not always the same when it comes to how they require consuming data. Libraries can require pure JSON, arrays, Strings, even single integers. This is why it’s important to get to grips with how the library you are working with can consume data, and hopefully, this is in a variety of ways too.

So how does ChartJS require data?

ChartJS likes to consume its data mainly by using the Array type, whether that be an array of numeric or string values alike. This is pretty great because JavaScript arrays are really simple to setup and work with. If you haven’t been exposed to JavaScript Arrays yet, then read this great article on them. The only exception to this default behaviour is Scatter Charts which, require x and y coordinates in a JSON format.

If you’ve already been through the last article, Creating a Bar Chart with ChartJS, you will have seen how data can be passed into the libraries main function. Let’s re-cap on how data is passed in or specified ‘inline’.

The Data Property

Data is a property of the master JSON object that the main Chart function requires as a parameter. It exposes a sub-set of properties that can be populated. Here are the most important properties that need to be understood.

    • labels – An array of x-axis Labels in either Numeric or String form.
    • dataSets, which exposes another sub-set of properties
        • data – An array of data-point values that are parallel to the labels specified.
        • backgroundColor and borderColor A pair of String Arrays that consist of Hexadecimal or RGBA color values to color the bars and borders or other various visualizations.
        • borderWidth which takes a single Integer or Float value, this of course, specifies border widths across the data visualizations.

Understanding these properties will enable fluent construction of charts with any data, whilst knowing in most cases, the data will sit in an array and can be filled in a range of ways. Let’s see this in the flesh –

Example taken from the ChartJS Documentation

data: {
	labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
	datasets: [{
		label: '# of Votes',
		data: [12, 19, 3, 5, 2, 3],
		backgroundColor: [
			'rgba(255, 99, 132, 0.2)',
			'rgba(54, 162, 235, 0.2)',
			'rgba(255, 206, 86, 0.2)',
			'rgba(75, 192, 192, 0.2)',
			'rgba(153, 102, 255, 0.2)',
			'rgba(255, 159, 64, 0.2)'
		],
		borderColor: [
			'rgba(255,99,132,1)',
			'rgba(54, 162, 235, 1)',
			'rgba(255, 206, 86, 1)',
			'rgba(75, 192, 192, 1)',
			'rgba(153, 102, 255, 1)',
			'rgba(255, 159, 64, 1)'
		],
		borderWidth: 1
	}]
}

The DataSets Property

By now, you will have realized that datasets is pluralized, meaning it is capable of having more than one data set. This is when some JSON knowledge is helpful, because the datasets property will need nested objects for multiple series of data. Here’s an example of a two date series nested inside the datasets property.

data: {
	labels: ["Tokyo", "Mumbai", "Mexico City", "Shanghai", "Sao Paulo", "New York", "Karachi", "Buenos Aires", "Delhi", "Moscow"],
	datasets: [{
			label: 'Series 1',
			data: [500, 50, 2424, 14040, 14141, 4111, 4544, 47, 5555, 6811], 
			backgroundColor: [ 
				'rgba(255, 99, 132, 0.2)',
				'rgba(54, 162, 235, 0.2)',
				'rgba(255, 206, 86, 0.2)',
				'rgba(75, 192, 192, 0.2)',
				'rgba(153, 102, 255, 0.2)',
				'rgba(255, 159, 64, 0.2)'
			],
			borderColor: [ 
				'rgba(255,99,132,1)',
				'rgba(54, 162, 235, 1)',
				'rgba(255, 206, 86, 1)',
				'rgba(75, 192, 192, 1)',
				'rgba(153, 102, 255, 1)',
				'rgba(255, 159, 64, 1)'
			],
			borderWidth: 1 
		},
		{
			label: 'Series 2', 
			data: [1288, 88942, 44545, 7588, 99, 242, 1417, 5504, 75, 457], 
			backgroundColor: [ 
				'rgba(255, 99, 132, 0.2)',
				'rgba(54, 162, 235, 0.2)',
				'rgba(255, 206, 86, 0.2)',
				'rgba(75, 192, 192, 0.2)',
				'rgba(153, 102, 255, 0.2)',
				'rgba(255, 159, 64, 0.2)'
			],
			borderColor: [ 
				'rgba(255,99,132,1)',
				'rgba(54, 162, 235, 1)',
				'rgba(255, 206, 86, 1)',
				'rgba(75, 192, 192, 1)',
				'rgba(153, 102, 255, 1)',
				'rgba(255, 159, 64, 1)'
			],
			borderWidth: 1 
		}
	]
}

This type of nesting can be multiplied many times, allowing you to create large multi-series data visualizations with ease. Throughout this series, there will be examples of both single and multi-series charts to play with and use in your own projects.

Hopefully this article will bring more clarity to how ChartJS manages data and in addition, help you become more content with working with these important properties too. If you have any queries, please leave a comment and I will get back to you as soon as I can.

Setting Up With ChartJS

To get started, ChartJS have already made many scenarios effortless to get up and running. Let’s go through each way of using ChartJS in your own project.

1. Source Download

Depending if you want to play with the many samples provided by ChartJS, you could download the full source code. Similarly, you may want to edit the source code to suit certain needs within your project too, in this case, downloading the source would be best.

Personally I like to get the full source code so that examples and documentation are easily to access, even when offline.

To get the full source code, follow these steps.

  1. Goto the latest repository on GitHub here.
  2. Download the link named ‘Source code (zip)’
  3. Extract the contents of the folder somewhere safe.
  4. Copy the Chart.js file from the dist/ folder to your project.
  5. Finally, reference the Chart.js file in your HTML code.

Wallah, you are ready to start coding!

2. Content Delivery Network

ChartJS is on the CDNJS website and therefore can be referenced directly from your project as-long as you have an internet connection. This is by far the quickest to get going, but obviously it has the drawback of always having to be on-line. To setup with CDN, see the following steps

  1. Goto https://cdnjs.com/libraries/Chart.js
  2. Copy the link source you want to use, for example ‘https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js‘.
  3. Add this link within a script tag into your HTML code.

3. Package Managers

If 1 and 2 aren’t how you like to add libraries to your project, there are a few alternatives. Namely, NPM & Bower. See the following commands to download the ChartJS package into your project. Remember to reference the scripts within your HTML code, though.

NPM

npm install chart.js --save

Bower

bower install chart.js --save

Integration

ChartJS website provides details on integrating their library with your current environment, this includes integrating with ES6 and common JS. Check it out here.

Creating And Working With Bar Charts

Lets start seeing some magic happen with working data visualizations, and what better way to start than a simple bar chart? I have already gathered some public data for the use within the tutorial so that you can copy it and easily add it to your own code-playground. In addition, I will create all demonstrations in a CodePen that you can fork, copy and save. In this tutorial, there is no need for any back-end programming as such, just pure HTML, CSS and JavaScript.

Lets get started

If you haven’t already set-up, take a look at the Getting Started With ChartJS article and then come back here.

Each chart of the ChartJS library requires a HTML5 Canvas placeholder, solely required to render beautiful charts onto. If you haven’t seen the canvas tag already, it looks like the following –

<canvas>

This moves us onto the very first part of the tutorial, adding our HTML element. Add this element to your HTML code –

HTML

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

The canvas ID is very important when using this library and if you can help it, use something more descriptive rather than ‘myChart’, especially if you have more than one chart on the page.

The ID will be used to instruct the charting library where to render the fully configured chart. With this in mind, lets start to add some script by creating a canvas context by specifying the ID we used in the HTML.

JavaScript

var ctx = document.getElementById("myChart").getContext('2d');

Now we need to specify some data values & labels, as I mentioned before, I’ve already got some great public data prepared, see the following JavaScript –

// Define the data 
var data = [22006299,	15834918,	14919501,	14797756,	14433147,	13524139,	11877109,	11862073,	11779606, 10452000]; // Add data values to array

var labels = ["Tokyo",	"Mumbai",	"Mexico City",	"Shanghai",	"Sao Paulo",	"New York",	"Karachi","Buenos Aires",	"Delhi","Moscow"]; // Add labels to array
// End Defining data

Now lets setup the ChartJS object, passing in the canvas context we created earlier and pass in the arrays of data –

var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: labels,
        datasets: [{
            label: 'Population', // Name the series
            data: data, // Specify the data values array
            backgroundColor: [ // Specify custom colors
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [ // Add custom color borders
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1 // Specify bar border width
        }]
    },
    options: {
      responsive: true, // Instruct chart js to respond nicely.
      maintainAspectRatio: false, // Add to prevent default behaviour of full-width/height 
    }
});

Some notable points from above –

  • ChartJS requires a type, in this case, bar for bar chart.
  • Passing in data is relatively easy, specifying the series, labels and values.
  • Style each bar precisely how you want them to look with background, border colors and even border width.
  • Set responsive to true so that the chart responds to the screen-width, leaving pixel perfect visualizations across different screen-sizes.
  • Lastly, Make the Maintain Aspect Ration option false, so that it doesn’t render as the full screen width and height. – You can remove this option to see exactly what I mean.

Let’s see how this all looks!

See the Pen Bar Chart Example With ChartJS by Danny Englishby (@DanEnglishby) on CodePen.0

 

Creating And Working With Line Charts