Tagged: ChartJS, Data visualization, ReactJS
- This topic has 0 replies, 1 voice, and was last updated 10 months, 2 weeks ago by
Precious.
- AuthorPosts
- February 25, 2020 at 4:43 pm #86647Participant@precious
As a developer, you might come across situations where there is a need to visualize data in your program using charts and graphs as a way of making analysis and decision making easy. Some programming languages have inbuilt tools for this, and some do not – hence they employ the services of third-party libraries and play alongside them to achieve this.
For ReactJS, there are many third party libraries that can be installed to and called upon by React to achieve this. One of the most efficient and flawless is ChartJS. This tool is an open-source JavaScript library fully made for the visualization of data in all forms possible. ChartJS supports about 8 types of charts, enlisted below.
- Bar Charts
- Line Charts
- Area Charts
- Bubble Charts
- Radar Charts
- Polar Charts and
- Scatter Charts
Depending on when you came across this article, some more charts could be added or removed (since it is constantly undergoing updates and is open-source).
This article explains the procedure for visualizing your data in ReactJS using ChartJS.
Requirements
You will need to setup your environment with these tools to make this procedure work.
- Visual Studio Code Editor
- NodeJS framework. To do this, simply open this link , download and install NodeJS (I recommend you use the current version).
- The NodeJS package manager (NPM). This package comes alongside the installation of NodeJS (It is installed alongside Node).
- ReactJS library. To install this package, simply open the command prompt interface in administrative mode and run
npm install create-react-app
. - ReactJS application. After react has installed, run
npx create-react-app chart_app
– note that chart_app as used here is the name of your react application. You could use any name of your choice.
After the application is setup, type in
npm start
to ensure that the project is up and running. (It should show up in your browser).Step 1: Install ChartJS and its Wrapper
After the creation of your application. You will need to install two packages – one will hold the ability to create charts and the other will allow the charts to be run on your React application. These two packages are;
- ChartJS: This is the javascript library package that offers the ability to visualize data passed into it.
- React-chartjs-2: This package serves as a wrapper that gives the React application the necessary components that make it compatible with ChartJS. The version currently in use (and also the most stable) is the 2nd version which was created to fit in with ChartJS (version 2) and eliminate any compatibility issues.
To begin, you only need to install them using your node package manager (NPM). Open a terminal in your project and run the following code
npm install react-chartjs-2 chart.js --save
– this should run and install both packages on your application.If the installation is successful you should see an output like the image below (do not worry about the warnings).
After this is done, create a folder named components inside your source (src) folder, then create a file inside the components folder and name it react_chart.js. Copy and paste the following source code into the file.
123456789101112131415161718import { Pie } from 'react-chartjs-2' //The tool used here is Pie because we will be making a pie chart first.import React, { Component } from 'react'import { render } from '@testing-library/react';class Chart extends Component { //Stateful class componentrender() {return (<div></div>);}}export default Chart; //export your class so you could call it up from the main component (App.js)With this, you have installed ChartJS, its wrapper (react-chartjs-2) and they are positioned where necessary in your project.
Step 2: Prepare the Basic Data for Visualization
Here, we define the type of chart we want and the features of the chart. We also add the data we need to be visualized.
- From the previous step, the code suggests we use a Bar Chart. So, inside the return method in Chart.js, enter the following code. (Notice that the Pie tag is written as
NOT
)
12345678910<Piedata = {this.state.chartData}width = {576}height = {480}options = {{}}/>- Create a constructor above the render method – this is where all your data would come from, including the styling (color, labels etc). For this article, we would use a set of foods and their observed consumption rates over a period of time as our data. To create this constructor and add the data, enter the following code just above the render method in the Chart.js file.
1234567891011121314151617181920212223242526constructor(props) {super(props);this.state = {chartData: {labels: ['Pizza', 'Bread', 'Rice', 'Pasta', 'Noodles', 'Cereals'],datasets: [{label: 'Consumption',data: [51757, 32255, 87675, 81815, 90009, 89898],backgroundColor: ['red','orange','yellow','green','blue','indigo','violet']}}}}- Save your Chart.js file.
- Then open App.js and import Chart.js into the application using this code
import Chart from './components/Chart'
– do this at the topmost part of the file (App.js). - Also insert an instance of Chart.js into App.js – simply get into the return method (inside App.js) and add
.
- Save both files and open your browser. Your chart should look like the image below.
That’s it! You have effectively prepared and visualized your data. But that is not all!
Step 3: Add properties and Visualize Multiple datasets
The chart displayed above is a Pie Chart without a Title whose legends are fixed. This step explains some helpful information regarding your decision to add a title and position the legends (the active parts of the chart) where you want them to be. You could also represent more than one array of data on the chart (depends on the type of chart you are using).
To add a title and re-align the legends (guide for knowing which color represents each data in the chart), return to the Chart.js file and add the modify your code to look like the code snippet below;
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960import { Pie } from 'react-chartjs-2' //The tool used here is Pie because we will be making a pie chart first.import React, { Component } from 'react'class Chart extends Component { //Stateful class componentconstructor(props) {super(props);this.state = {chartData: {labels: ['Pizza', 'Bread', 'Rice', 'Pasta', 'Noodles', 'Cereals'],datasets: [{label: 'Consumption',data: [51757, 32255, 87675, 81815, 90009, 89898],backgroundColor: ['red','orange','yellow','green','blue','indigo','violet']}}}}render() {return (<div className = 'chart'><Bardata = {this.state.chartData}width = {576}height = {480}options = {{maintainAspectRatio: false,title: {display: true,text: 'Most Consumed foods in the Tropics', //This is just a made up title, you can add yoursfontSize: 30},legend: {display: true,position: 'bottom'}}}/></div>);}}export default Chart; //export your class so you could call it up from the main component (App.js)Then save your file and refresh your browser, your outlook should show a title for the chart and the legends at the bottom – just like the screenshot below.
To prepare and visualize multiple data, a pie chart would not be suitable because it would simple add one pie directly on another, thus it is necessary to change the type of chart you would want to use. Follow these steps to achieve multi-data visualization.
- Change the chart type from Pie to Bar in your imports (Chart.js).
- Add a new set of data inside your constructor (Chart.js)
- Save your file.
To make this easy, simply replace all your code in Chart.js with the following codes;
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879import { Bar } from 'react-chartjs-2' //The tool used here is Bar because we will be making a Bar chart.import React, { Component } from 'react'//import { render } from '@testing-library/react';class Chart extends Component { //Stateful class componentconstructor(props) {super(props);this.state = {chartData: {labels: ['Pizza', 'Bread', 'Rice', 'Pasta', 'Noodles', 'Cereals'],datasets: [{label: 'Consumption',data: [51757, 32255, 87675, 81815, 90009, 89898],backgroundColor: ['red','orange','yellow','green','blue','indigo','violet']},{label: 'Cost per 1000 units',data: [45800, 36000, 39000, 31900, 34500, 27000],backgroundColor: ['brown','magenta','purple','gray','pink','navy','purple']}]}}}render() {return (<div className = 'chart'><Bardata = {this.state.chartData}width = {576}height = {480}options = {{maintainAspectRatio: false,title: {display: true,text: 'Most Consumed foods in the Tropics', //This is just a made up title, you can add yoursfontSize: 30},legend: {display: true,position: 'bottom'}}}/></div>);}}export default Chart; //export your class so you could call it up from the main component (App.js)A good look at the constructor would reveal two sets of data – each bearing the Consumption and Cost per unit.
Save your work and refresh your browser. The outlook should look like the screenshot below.
With this. You are fully set to visualize single and multiple datasets with ChartJs – while using ReactJS as your wrapper.
The next part of this article will discuss how to visualize data extracted from a database with ReactJS and ChartJS – thus involving the server-side and the database management system.
Stay tuned.
- AuthorPosts
- You must be logged in to reply to this topic.