A Beginner’s Guide to Creating Beautiful Charts using Chart.js + React

Natalie Rojas
6 min readApr 8, 2021
Photo by Carlos Muza on Unsplash

Objective

Chart.js is a simple yet powerful tool for data visualization. In this article, I will walk through how to create a mixed chart that combines bar graph and line graph, and how to style and add animation by changing the configuration. This article is meant to cover the basic implementation of charts using Chart.js within React project.

Stack bars + Line chart combination

What is Chart.js?

Chart.js is one of the most popular libraries to create beautiful charts. To those who are not familiar, Chart.js is a free open source JavaScript library that supports 8 different chart types. (Line, Bar, Pie, Doughnut, Radar, Bubble, Scatter, Polar) It renders HTML canvas element to create these charts.

Chart.js takes away the complexity and allows you get started quickly on creating some of the popular charts. It also comes with default styling and animation which allows you to create beautiful charts with just a little bit of code. Some built-in styling includes a legend display and pop-up of data values when hovering the charts. The default styling can easily be changed using configuration, allowing flexibility in styling the charts based on your app’s aesthetics.

In this article, I will be demonstrating how to use the React wrapper for Chart.js which is another library that makes it easy to use Chart.js in your React project.

Starting Point

Let’s begin by initializing app through create react app.

npx create-react-app chartjs-tutorial
cd chartjs-tutorial
npm start

Create react app lets you get started on your react app in a quick and easy way. It comes with backend server that that is hidden behind the hood, so you don’t need to worry about setting up the server, and quickly get started on building your frontend. For more information about create-react-app, you can check out the documentation here.

Next we can install Chart.js and Chart.js for React:

npm install react-chartjs-2 chart.js

In src file, we can create components folder and inside, add Main.js, and MixedChart.js, to separate each charts within different components. The file structure would look like below.

src
-App.js
-components
-Main.js
-MixedChart.js

The purpose of separating Main.js and the chart component is in case of scaling and adding multiple charts later on. If you are using one dataset to render different types of charts, Main.js can be where datasets are retrieved (such as through API calls to get the data you need), and pass on the relevant data as props to different chart components.

Main.js File:

import React from "react";
import MixedChart from "./MixedChart";
import RadarChart from "./RadarChart";
import PieChart from "./PieChart";
export default function Main() {//You can make API call to get the necessary data here
//and pass as props to relevant chart component
return (
<div>
<MixedChart data = {data}/>
<RadarChart data = {data} />
<PieChart data = {data} /> ... etc
</div>
);
}

Creating Line & Stacked Bar combination

Inside the MixedChart.js, import “Bar” chart from react-chartjs-2. The imported Bar is a react wrapper that allows you to render Bar graph.

Like mentioned above, Chart.js have 8 different chart types and each can be used by importing specific chart type you need (Example : import { Bar, Line, Pie, Doughnut, Radar } from ‘react-chartjs-2’)

import React from "react";
import { Bar } from "react-chartjs-2";
const MixedChart = () => {
return (
<div className="charts-card">
<Bar
data={data}
options={options}
/>
</div>
);
};
export default MixedChart;

By passing necessary props to this “Bar” component, we can create charts based on our data.

  • Data props
  • Options props

Data props

Data props should be an object that includes basic information about your data. For example following should be added to define your chart:

  • Labels: String or number that represents values on X axes
  • Datasets: Array of objects that each represents Y value data. If you want to add multiple datasets to your chart, you can add to this array.

Inside the Datasets array, each object should include :

  • Label : Name of the data — this will become legends on the chart
  • Data : Numerical value representing the Y axes — This should be in the same order as the defined labels (X axes values). In below example, “Jan” label is for “3” from data1, and “2” from data2.

You can add styling within this data object, such as the background color, opacity of the bars, and the border color etc. To see the full list of all the attributes that are accepted in the data prop, see the documentation here.

*Data needs to be converted to array in order to add as values in the object. You can find more information about accepted data format here.

//Example of 3 different data sets 
const data1 = [3, 1, 5, 8, 20, 10, 15, 30];
const data2 = [2, 3, 10, 5, 5, 9, 10, 10];
const total = data1.map((num, idx) => num + data2[idx]);
//Inside data props
const data = {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug"],
datasets: [
{
label: "Data1",
data: data1,
backgroundColor: "rgba(87, 121, 234, 0.6)",
borderColor: "rgba(87, 121, 234, 0.6)",
order: 1,
},
{
label: "Data2",
data: data2,
backgroundColor: "rgba(18, 200, 150, 0.6)",
borderColor: "rgba(18, 200, 150, 0.6)",
order: 1,
},
{
label: "Total",
data: total,
backgroundColor: "rgba(234, 87, 102, 0.6)",
borderColor: "rgba(234, 87, 102, 0.6)",
fill: false,
pointHoverRadius: 20,
pointHoverBorderWidth: 5,
type: "line",
order: 0,
},
],
};

In the code snippet above, total of 3 datasets are added inside the datasets, each represented as an object with label, data, and styling details.

Adding Line Graph inside Bar Graph

Since this data will be passed as props on the “Bar” component, Data1 and Data2 will become bar graph by default when rendered. The last object in the array with label “Total” has an additional attribute, with type “line” to indicate that this should be represented as a line graph inside the bar chart.

The order attribute indicates which datasets should be sitting on top. Charts can be created with passing “data” as the only props, but at this point, the chart will look like 2 bars next to each other and a line graph.

To make “stacked bar” chart, we need to add options props to create custom configuration to your chart.

Options props

For all types of charts, specific configuration can be added by passing in “options” prop. Some of the examples are below:

  • Title: Main title of the chart, if none is needed, you can set display to false
  • Scales: Add X axes and Y axes’ labels
  • Animation: We can change the out of the box animation by adding configuration to the animation attribute.
  • Others: you can also add styling for legends (whether to display or to change sizes), styling and customizing the aspects of scales such as ticks and grids , and many more.
const options = {
responsive: true,
maintainAspectRatio: false,
animation: {
duration: 3000,
easing: "easeInBounce",
},
title: {
display: true,
text: "Bar + Line Chart",
fontSize: 25,
},
scales: {
xAxes: [
{
scaleLabel: {
display: true,
labelString: "Months",
},
stacked: "true",
},
],
yAxes: [
{
scaleLabel: {
display: true,
labelString: "Values",
},
stacked: "true",
},
],
},
};

In above code snippet, title and labels for X & Y axes are added. And to stack the bars for 2 types of datasets passed, simply add “stacked: true”. That’s it, with this, we were able to create mixed chart with stacked bars and line chart representing the total values for 2 datasets.

Animation added to the chart

Conclusion

If you understand how the data needs to be formatted and the types of accepted attributes and the layers of where it should be defined, then you should be able to easily apply the same logic to create other types of charts.

There are many more features and styling that can be added to create beautiful and unique charts for your project. You can see sample charts created by Chart.js here to explore more. Thank you very much for reading !

--

--

Natalie Rojas

Full Stack Software Engineer based in New York. Passionate about building apps that solves every day problems