JavaScript Graphs – React and Chartjs

Data Visualisation

Data visualisation is the representation of information in the form of charts, diagrams, metrics etc.

These charts are created as the visual representation of data sets. Charts and graphs are utilized by those who want to use metrics or analytics to further their relative understanding of desired data.

From a non technical perspective humans process visual input above all else and faster than any other method.

Generally, this is the key reason for wanting to visualize data. Patterns are easier to digest, and vital decisions are more easily made when dynamic data is depicted visually.

As a developer, if you can provide data visualisation solutions for your clients your value can increase tenfold.

When done correctly, data visualisation design and implementation can provide infinite value for a client. In return, you should expect a serious percentage of that value for your services.

Taking all this in consideration we can see why data visualisation is an extremely important aspect of some SaaS (Software as a service) services. And why it can be a very useful aspect of JavaScript for any web developer learn.

I have recently added data visualisation into a React web app service that was recently created called coin-profit.

Please feel free to check it out.

Choosing a Library

Coming from a React background there are many data visualisation libraries to choose from.

However, my personal preference is Chartjs, which provides a series of very customisable charts that can be easily manipulated to depict dynamic information.

The best way to utilise this in a React project is to download a package that imports the various Chartjs graphs as modules to use in your React Component.

In your node console use the command:

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

So, far so good but what data are we going to use?

Well, for this post I am using calculations  based on data that I previously retrieved from  Crypocompare.

If you want to see how to retrieve crypto data you can look at React & HTTP – Retrieving Crypto Data

Donut Chart Component

So lets create a donut chart component that will import our Chartjs modules. Please note that I’m using TypeScript in order to provide typed definitions of my data.

If you looking to learn more about TypeScript and React you can check out Improve you codebase using types.

So here is our Donut component receiving its props and state.

import * as React from 'react'
import { ClipLoader } from 'react-spinners'
import { Redirect } from 'react-router-dom'
import { Doughnut } from 'react-chartjs-2'
import { Total }  from '../../types/Total'

export type State = {
  redirect: boolean
}

export type Props = {
  total: Total
}

class Donut extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props)

    this.state = {
      redirect: false,
    }
  }

  render() {
   
  }

export default Donut

We are receiving a prop called total of type Total which is defined separately in a definition file:

 export interface Total {
    id?: number
    coinAmount?: string
    gainPercent?: number
    costPrice?: number
    sellPrice?: number
    lostPercent?: number
}

We now want to render our Donut Chart component from the react library. In order to do this the component requires a set of customisable options in order to function correctly.

These options include but aren’t limited to:

  • The dataset the chart will render
  • The colours of its segements
  • Types of fonts for labels
  • Color of fonts
  • Names of labels

Again, these options are completely customisable so you can create a chart that fits the requirements of your data visualization goals.

One of the main advantages of using this in combination with React is that you can dictate the options of the chart based on your state and props.

For example:

render() {
    const total = this.props.total
      let data = {
      datasets: [
        {
          data: [`${total.costPrice}`, `${total.sellPrice}`],
          backgroundColor: [
            'rgba(54, 162, 235, 0.2)',
            `${total.gainPercent ? 'rgba(75, 192, 192, 0.2)' 
                                 : 'rgba(255, 99, 132, 0.2)'}`,
          ],
          borderWidth: 0,
        },
      ],
      options: {
        responsive: true,
        segmentShowStroke: true,
        legend: {
          labels: {
            fontColor: 'white',
            fillStyle: 'white',
            margin: 20 + 'px',
            fontFamily: `"Roboto Mono",Helvetica,Arial,sans-serif`,
          }
      }
      },
      // These labels appear in the legend and in the tooltips when hovering different arcs
      labels: ['Cost Price', `${total.gainPercent ? 'Profit' : 'Loss'}`],
    }

 return (

) } }

A good example of this is the use of ES6 template literals and a ternary operator the background colours to change total.gainPercent

I have setup my Total object to have two properties gainPercent> and losePercent. If one exists its safe to assume the other doesn’t. In otherwords there either has been a profit or a loss.

I want the chart to show an appropriate color depending on a profit or the loss and the use of ternary operator ensures that here:

 backgroundColor: [
            'rgba(54, 162, 235, 0.2)',
            `${total.gainPercent ? 'rgba(75, 192, 192, 0.2)' 
                                 : 'rgba(255, 99, 132, 0.2)'}`,
          ],

The donut chart will segments will be correctly styled if there has been a profit or a loss.

In the same way, the total.gainPercent property can help dictate the relevant labels.

 labels: ['Cost Price', `${total.gainPercent ? 'Profit' : 'Loss'}`],

The label profit or loss will be shown depending on the existence of the gain percentage property.

These are simple demonstrations however they indicate the possibilities to make your chart dynamic based on your selected data.

Our DonutChart component will be re rendered anytime this data changes

Overall, React & Chart.js combine very effectively. Chart.js’s customiseable options in combination with React’s re-rendering is natural fit when creating a dynamic charts from your data.

Chartjs will provide you wide range of different charts for you to use. In my coin profit application I have utilised line charts, bar charts, donut charts and the process of implementating these with my desired data was notably smooth.

I will be covering a lot more data visualization topics on JSdiaries so make be sure to stay around. If you have any questions or are interested in some data visualisation services don’t hesitate to get in touch.

Proudly published with Gatsby