Data Visualization Using Chart.js and Gatsby
Tags: gatsby, javascript, webdev, programming
Published: 2022-05-15 18:27:24

Data visualization is a way of presenting large unorganized datasets in an organized and valuable way. Data representation can take on many different forms like charts -  bar, pie, doughnut, line, and so on. Our job as developers in this context is to take these complex data and make them easy for everyone to understand.

In this article, you will better understand how to use a JavaScript library, in this case, Chart.js, to visualize data to save time and effort and improve performance and efficiency. That is what data visualization entails, and we can achieve this with some lines of code in Gatsby.

Let's get started with the areas of interest covered in this post:

- What is Gatsby?

- Sandbox

- Prerequisites and Installation

- Why is Data Visualization important?

- Data Visualization: using Chart.js

- Data Visualization: Chart Creation

- Final Thoughts on Data Visualization

## What is Gatsby?

Gatsby, a React-based framework, makes building websites faster by making them secure, search engine friendly, and better optimized (in terms of SEO). Gatsby utilizes modern technologies like React and GraphQL.

## Sandbox

The entire project is on [Codesandbox](https://codesandbox.io/s/musing-maxwell-24633). Fork it to run the code.

## Prerequisites and Installation
This article will assume you understand using React, as it is required to complete the project. However, you don't need to know Gatsby to implement the chart on the client-side.

Before building, we need to set up our development environment by installing Gatsby globally using its Command Line Interface (CLI). This process serves as the main entry point for kickstarting a Gatsby application.

The Gatsby CLI is available via npm and installed using this command:

`npm install -g gatsby-cli`

Run the following command to check the version of gatsby you are currently running:

`gatsby –version`

To create a new project in our desired directory. We need to scaffold and generate the files required to run a gatsby application using the command.

`gatsby new`

Running the above command in your terminal will start an interactive prompt to help you create a new Gatsby site. For a guide to complete the process, check [here](https://www.gatsbyjs.com/docs/tutorial/part-1/).

To start the local development server on `http://localhost:8000`, **cd** into the newly created Gatsby site with the command:

`cd gatsby-chart`

And to run the app, use the command:

`npm run develop`

## Why is Data Visualization Important?
Data visualization is essential to assist businesses, individuals, and consumers in making informed decisions on data trends that would otherwise have been difficult. The applications of data visualization in today's world are numerous, from the media field and speaker deck presentation to advertising and so on. The value of data visualization outweighs the disadvantages, as the insights presented can help:

- Increase the speed of decision making

- Provide access to real-time information and stats on the go

- Conveys the right message to the audience without too many words

- Make sense of complicated data

## Data visualization: using Chart.js

To begin building a standard chart that we can all use on our websites, we need to install some dependencies in our Gatsby site using the CLI command:

`npm install chart.js react-chartjs-2`

`chart.js` - A simple yet flexible JavaScript charting library

`react-chartjs-2` - React components for Chart.js give us many different chart components we can utilize.

We will be working from the `pages/index.js` file, and you can delete the `404.js` as we won't be needing it. Delete everything within the `IndexPage` component, and you should have this looking the same below.

```javascript
// pages/index.js

import * as React from 'react';
 
const IndexPage = () => {
 return (
   <main>
     <title>Charting made fun</title>
     <h1>Build a chart component</h1>
   </main>
 );
};

export default IndexPage;
```

## Data Visualization: Chart Creation

Now is the time to get our chart working. But first, we will need to create a directory called `components` in the `src` directory. Then, we make a file `PieChart.js` that contains all the components.

```javascript
// src/components/PieChart.js

import * as React from 'react';

const PieChart = () => {
 return <p>Pie chart</p>;
};

export default PieChart;
```

We need to import the file into the index page for the created pie chart component to show on the browser.

```javascript
// src/pages/index.js

import * as React from 'react';
import Pie from '../components/Pie;
 
const IndexPage = () => {
 return (
   <main>
     <title>Charting made fun</title>
     <Pie />
   </main>
 );
};

export default IndexPage;
```

As stated above, the rendered message pie chart should display in the browser if you did everything correctly.

Let's create the pie chart from the library `react-chartjs-2` to utilize the Pie chart. However, other components (types of data visualization that we can use to represent our data in Gatsby) came preinstalled when we installed the dependency like the Chart, Line, Bar, Bubble, PolarArea components, and so on. So it depends on what you want to achieve as you can always reference the [documentation](https://react-chartjs-2.netlify.app/components).

```javascript
// src/components/PieChart.js

import * as React from 'react';
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js';
import { Pie } from 'react-chartjs-2';

ChartJS.register(ArcElement, Tooltip, Legend);

export const data = {
 labels: ['Taxation', 'Materials', 'Profit', 'Expenses', 'Wages'],
 datasets: [
   {
     label: 'Tax bill',
     data: [25, 20, 8, 12, 34],
   },
 ],
};

const PieChart = () => {
 return (
   <div style={{ width: '750px' }}>
     <Pie data={data} />
   </div>
 );
};

export default PieChart;
```

In the above code block, we need to import and register the ArcElement, Tooltip, and Legend we are using. Also, we created an object of data containing the labels for the Pie chart and the data we will pass as props when rendered in JSX. With that done, here is what our Pie chart should look like without colors in the image below:


![chart without colours](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ht5619a0tdgbf2mini2.png)

The following steps are to fill the labels, the border, and the pie chart with background color in an array and the border width. We do this to improve the aesthetic value of the project.

```javascript
// src/components/PieChart.js

import * as React from 'react';
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js';
import { Pie } from 'react-chartjs-2';

ChartJS.register(ArcElement, Tooltip, Legend);
 
export const data = {
 // labels representing each of the tax bill 
 datasets: [
   {
     // label for the Pie chart
     // data in an array goes here

     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)',
     ],
     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)',
     ],
     borderWidth: 1,
   },
 ],
};

const PieChart = () => {
 return (
   <div style={{ width: '750px' }}>
     <Pie data={data} />
   </div>
 );
};

export default PieChart;
```


![chart with colour](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pf7gy6xeuru5gn0eif51.png)

## Final Thoughts on Data Visualization

As a developer, are you convinced that we need to simplify its presentation for a wider audience since data is everywhere? We can build these solutions that make it intuitive and interactive for anyone coming across it for the first time on your website.

In this article, we presented two necessary dependencies that can help build a Pie chart with some lines of code, using a Frontend framework, Gatsby, which makes it quick to spin up a website.

I recommend that you try it today and tweak those boring ways of presenting data. Use beautiful charts instead, for you and your team.

Find the complete source code on [GitHub](https://github.com/Terieyenike/gatsby-chart). And view the project live [here](https://gatsby-chart.vercel.app/).