Getting Started With Data Visualisation Using Chart JS & React
INTRODUCTION: Data Visualisation might sound like a big word, but essentially it is just visualising a given dataset for understanding it better. Data Visualisation is vital for sharing one’s research or even deriving meaningful insights and conclusions from raw data. There are many tools used for Data Visualisation, and one can dive deep into this field. For purposes of this study, we will learn how to create basic charts and graphs for given data using Chart js & React.
Why Chart JS?
Chart.js is a free, open-source JavaScript library for data visualisation, supporting eight chart types: bar, line, area, pie, bubble, radar, polar, and scatter. Folks at Wappalyzer have done a great job creating a list of charting libraries with their respective market shares.
As you can see, Chart JS is at the top with about 40% of the market! Why so, you may ask? The simple reason is that Chart Js is straightforward to use, has plugin support, and an incredible developer community (Also, most people don’t need advanced charts in their projects).
Want to read this story later? Save it in Journal.
NOTE: Here, I will be using Chart Js 3.3.2. You can follow this tutorial for any version of Chart JS 3.X
Why React?
React is an open-source front-end JavaScript library for building user interfaces or UI components. React is a rapidly growing Web development library. So I think it will be more practical and valuable to you if we go with it.
Now that we have the basic idea of what we want to achieve let’s jump right in!!
Charts JS supports 8 types of charts:
1. Line Chart
2. Bar Chart
3. Radar Chart
4. Doughnut Chart & Pie Chart
5. Polar Chart
6. Scatter Chart
7. Area Chart
Prerequisites:
- I will be using Visual Studio Code. Other text editors are also great. Have one installed and open.
- Have a React app ready. And have an understanding of where you want to put the charts.
Installation:
Out of the many ways to install Chart JS I find this the easiest and fastest.
(Write this code in terminal)
npm install chart.js
Importing into React:
Where you import your React component below that paste this snippet of code. This snippet will Import the Chart Js library into your JS file.
import Chart from 'chart.js/auto';
Components of a Chart
From here on, anytime I refer to a chart, I refer to a chart made using the Chart JS library.
A Chart has 3 main sections:
- Type of chart: type
- Data to plot and features of data: data
- Features of Chart: options
TYPE OF CHART
The type of chart is specified in type. It takes a string input that is the type of chart you want to make.
Inputs can be: line, bar, radar, doughnut, pie, polarArea, bubble & scatter
NOTE: If you want to make a mixed chart(i.e., say make bar and line chart both in one single graph), put a type parameter in the dataset.
type: 'bar'
DATA TO PLOT AND FEATURES OF DATA
This is where we put the data that we want to plot. Let’s consider making a line chart, then the color, line thickness, point size, point color, point radius, labels, etc., are all set here.
IMPORTANT: The tag data takes only object as input; simply put, data will accept {…} but not […].
This data object contains 4 main properties:
- datasets: array of objects: This is where we put the actual data. (Explained in detail below)
- label: string: The label for the dataset which appears in the legend and tooltips.
- order: number: The drawing order of dataset. It also affects order for stacking, tooltip, and legend. In other words, this number decides in which order your graph will be drawn. Say, for example, you have two datasets you want to show. Chart JS will plot the one with lesser order first.
- hidden: boolean: This is used when you want to show or hide a dataset. Say you want to have buttons that add or remove datasets from your chart when clicked, you can create an onClick function to reverse the hidden value (0 to 1 and 1 to 0).
DATASETS:
It is where the actual data is put. Dataset is an array of objects. Each object must contain data: array. You can put other features of the data here. Such as line color, border color, and fill (Read the Chart Js documentation for all the properties). Now there are two ways to write this data.
1. We can have 2 properties (labels : array) and (data : array) put the x axis labels or rather x coordinates in labels array and the data values i.e. the y coordinates in the data array.
Note: Preferred when you have to show multiple datasets say you want to show 3 lines in your line chart then better put x coordinates in labels and y coordinates in respective dataset objects.
const data = {
labels: [1, 2, 3, 4, 5, 6, 7],
datasets: [{
data: [65, 59, 80, 81, 56, 55, 40],
}]
};
2. Or we can have 1 property (data : array of objects) which has x and y coordinates as keys.
// Simple x coordinates
data: [{x: 10, y: 20}, {x: 15, y: null}, {x: 20, y: 10}]// Dates as x coordinates
data: [{x:'2000-10-25', y:20}, {x:'1999-08-05', y:10}]// String values as x coordinates
data: [{x:'Monday', y:10}, {x:'Tuesday', y:21}]
IMPORTANT: Don’t get confused between label inside datasets and labels inside data. labels inside data contain the x coordinates, whereas label inside each object of the dataset includes the name of that dataset.
IMPORTANT: Always make sure that your charting code is run after the component has mounted; otherwise, the code will go through an error “getContext of NULL.” If you are using a functional component, add useEffect; if you are using class components, add componentDidMount.
FEATURES OF CHART
This is where you decide the features of your chart, i.e., do you want gridlines or not, what should be the range on both the axis, and much more. Also, you can add plugins here. I will talk about few essential plugins later.
Let’s go one by one discussing some important properties in option.
- scales: object: for each axis, you should have a separate key, i.e., one for the x-axis and one for the y axis. In the respective sub-objects, you can set properties of that scale.
- animation: object: here, you can set the animation parameters. I generally use to change the duration of the animation.
- plugins: in my opinion, this is one of the main features of chart js. Plugins let you customise the charts according to your liking. Say you want to add zoom functionality or pan functionality, or you wish to color four parts of the chart in different colors, you can do all that. An important note, though, is that you have to register your plugin before using it, or your code may give an error.
Going in-depth about how to create plugins is out of the scope of this tutorial. But once you know how this library works, you can read the documents and figure them out as you go.
ADDING ZOOM AND PAN FUNCTIONALITY USING PLUGIN
These are two features that I feel most of you will require. It is easy, and plugins are already made for this, so there won’t be any need to create new ones.
Step 1: First we will install the plugin for zoom and pan.
npm install chartjs-plugin-zoom
Step 2: Import this plugin into our component and register it with Chart JS. (Write these 2 lines at the below where you imported Chart JS library)
import zoomPlugin from 'chartjs-plugin-zoom';Chart.register(zoomPlugin);
Done now we can change the properties of zoom and pan to your liking in options.
Let’s build our charts!!
Now that we know the building blocks of a chart. Let’s create our chart!
The first chart is a basic line chart which has 2 datasets. The second one is a multi chart having one dataset visualised as a line and other as bars.
In the buildLineChart function we have set the chart type only once, as we have only line chart.
In the buildMultiChart function we have set the chart type inside the datasets.
Take care that you are not merging 2 chart types that can’t be merged like say a line chart with a pie chart!
Some points to keep in mind though!
- Read the documentation wherever you get stuck. You have more than enough knowledge to understand the examples provided in the documentation and find a solution to your problem.
- 1. Chart Js is just a simple library to start data visualisation. After you have a grasp over it, venture into other libraries such as d3.js.
- Take full advantage of the excellent developer community Chart js has. Look for your doubts on Stack Overflow, ask questions, and help others along the way!
All the codes for this tutorial are uploaded on my Github.
Do connect with me on Linkedin at linkedin.com/in/manmohanlabh/
If you have any doubts mail me at labhmanmohan25@gmail.com
Thank you for reading till the end! I wish you very best for your Data Visualisation journey!
Enjoyed this post? Subscribe to the Machine Learnings newsletter for an easy understanding of AI advances shaping our world.