Introduction
Visualizing data is an essential aspect of modern web development, allowing users to grasp complex information quickly. Charts are instrumental in presenting data in a user-friendly and engaging manner. In this guide, we will explore React-Chartsjs-2, a popular library that provides an elegant and efficient way to create interactive and responsive charts in your React applications.
Link to code repo
Setting Up the Project
We are going to use create-react-app to get started quickly and focus on implementing the charts.
- Create a New React Project: Use Create React App (CRA) with the command npx create-react-app my-chart-app.
- Navigate to the Project: cd my-chart-app.
- Install Dependencies: Run npm install react-chartjs-2 chart.js. These are the core libraries to enable chart rendering.
- Organize Your Files: Consider creating folders and structure for different chart types, such as /graphs/Line, /graphs/Bar, etc.
Before we can create the charts, we need to register the necessary components with Chart.js. Create a file called registerCharts.ts:
import {
ArcElement,
BarElement,
CategoryScale,
Chart,
Filler,
Legend,
LineElement,
LinearScale,
PointElement,
RadialLinearScale,
Title,
Tooltip,
} from "chart.js"
export const registerCharts = () => {
Chart.register(
ArcElement,
BarElement,
CategoryScale,
Legend,
LineElement,
LinearScale,
PointElement,
Title,
Tooltip,
RadialLinearScale,
Filler
)
}
Then import it into App.tsx
and instantiate it with registerCharts()
. Doing this at the top of the file ensures all necessary elements are registered before they are used.
import { registerCharts } from './registerCharts';
registerCharts();
// ... rest of the App component
Styling the Charts
To ensure that our charts are displayed in an appealing and organized manner, we will add some CSS styling. Create a file called App.css
in your project's src
folder and add the following CSS code:
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
box-sizing: border-box;
background-color: #f4f4f4;
}
.graph-container {
max-width: 50%;
width: 100%;
background-color: #ffffff;
padding: 20px;
box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
margin: 30px;
}
Import the charts
Your App.tsx
file should look something like this
import "./App.css"
import { registerCharts } from "./registerCharts"
import LineChart from "./graphs/LineChart"
import BarChart from "./graphs/BarChart"
import DoughnutChart from "./graphs/DoughnutChart"
import ScatterChart from "./graphs/ScatterChart"
registerCharts()
function App() {
return (
<div className="container">
<h1>React charts examples</h1>
<div className="graph-container">
<LineChart />
</div>
<div className="graph-container">
<BarChart />
</div>
<div className="graph-container">
<DoughnutChart />
</div>
<div className="graph-container">
<ScatterChart />
</div>
</div>
)
}
export default App
Line Chart
A Line Chart is a powerful tool for representing trends over time. In this section, we'll create a Line Chart to display the monthly sales trends for two products, A & B.
Here's how you can achieve that:
Code:
const LineChart = () => {
const options = {
responsive: true,
plugins: {
legend: {
position: "top" as const,
},
title: {
display: true,
text: "Line Chart: Monthly Sales Trend for Products A & B",
},
},
}
const labels = ["January", "February", "March", "April", "May", "June", "July"]
const productASales = [120, 135, 125, 145, 160, 150, 170]
const productBSales = [80, 75, 95, 100, 110, 105, 120, 115]
const data = {
labels,
datasets: [
{
label: "Product A Sales",
data: productASales,
borderColor: "rgb(255, 99, 132)",
backgroundColor: "rgba(255, 99, 132)",
},
{
label: "Product B Sales",
data: productBSales,
borderColor: "rgb(53, 162, 235)",
backgroundColor: "rgba(53, 162, 235)",
},
],
}
return <Line options={options} data={data} />
}
export default LineChart
Result:
Notes:
- The
responsive: true
option in your configuration ensures that the chart resizes when the window changes, a great feature for a modern, responsive design. - The
legend
andtitle
plugins allow you to add a legend and a title to your chart, making it more informative. - We have used two datasets to represent the sales of Products A & B, each with its color scheme.
Bar Chart: Quarterly Revenue & Expenses Comparison
Bar charts are excellent for visualizing and comparing data points across categories. In this example, we'll create a bar chart to compare the quarterly revenue and expenses of a company.
Code:
import { Bar } from "react-chartjs-2"
const BarChart = () => {
const options = {
responsive: true,
plugins: {
legend: {
position: "top" as const,
},
title: {
display: true,
text: "Bar Chart: Quarterly Revenue & Expenses Comparison",
},
},
}
const labels = ["Product A", "Product B", "Product C", "Product D", "Product E"]
const data1 = [45, 75, 55, 90, 60]
const data2 = [65, 40, 70, 80, 50]
const data = {
labels,
datasets: [
{
label: "Q1 Sales",
data: data1,
backgroundColor: "rgba(75, 192, 192)",
borderColor: "rgb(75, 192, 192)",
borderWidth: 1,
},
{
label: "Q2 Sales",
data: data2,
backgroundColor: "rgba(255, 159, 64)",
borderColor: "rgb(255, 159, 64)",
borderWidth: 1,
},
],
}
return <Bar options={options} data={data} />
}
export default BarChart
Result:
Notes:
- Bar charts make comparing values easy, with the height of the bars representing the values.
- Customize the appearance by using different colors, borders, or additional configurations according to your design needs.
Doughnut Chart: Monthly Sales Representation
Doughnut charts are perfect for representing a part-to-whole relationship in your data. Let's use it to visualize monthly sales data.
Code:
import { Doughnut } from "react-chartjs-2"
const DoughnutChart = () => {
const labels = ["January", "February", "March", "April", "May", "June", "July"]
const dataValues = [100, 50, 80, 60, 70, 40, 90]
const data = {
labels,
datasets: [
{
data: dataValues,
backgroundColor: [
"rgba(255, 99, 132)",
"rgba(53, 162, 235)",
"rgba(255, 206, 86)",
"rgba(75, 192, 192)",
"rgba(153, 102, 255)",
"rgba(255, 159, 64)",
"rgba(201, 203, 207)",
],
borderColor: [
"rgb(255, 99, 132)",
"rgb(53, 162, 235)",
"rgb(255, 206, 86)",
"rgb(75, 192, 192)",
"rgb(153, 102, 255)",
"rgb(255, 159, 64)",
"rgb(201, 203, 207)",
],
borderWidth: 1,
},
],
}
const options = {
responsive: true,
maintainAspectRatio: true,
aspectRatio: 2,
plugins: {
legend: {
position: "top" as const,
},
title: {
display: true,
text: "Doughnut Chart: Monthly Sales",
},
},
}
return <Doughnut data={data} options={options} />
}
export default DoughnutChart
Result:
Notes:
- The cutoutPercentage option allows you to adjust the thickness of the doughnut ring.
- Using distinct background colors enhances the visual appeal and helps in distinguishing different segments.
Scatter Plot: Monthly Sales vs Expenses
A scatter chart is excellent for visualizing relationships between two numerical variables. In this example, we'll create a scatter plot that shows the correlation between monthly sales and expenses for a business, helping you to identify trends and make informed decisions.
Code:
import { Scatter } from "react-chartjs-2"
const ScatterChart = () => {
const labels = ["January", "February", "March", "April", "May", "June", "July"]
const dataPoints = [
{ x: 20, y: 80 },
{ x: 30, y: 70 },
{ x: 50, y: 60 },
{ x: 40, y: 50 },
{ x: 70, y: 40 },
{ x: 60, y: 30 },
{ x: 90, y: 20 },
]
const data = {
labels,
datasets: [
{
label: "Scatter Chart: Monthly Sales vs Expenses",
data: dataPoints,
backgroundColor: "rgba(53, 162, 235)",
borderColor: "rgb(53, 162, 235)",
borderWidth: 1,
pointRadius: 5, // Adjust the size of the points
},
],
}
const options = {
responsive: true,
scales: {
x: {
beginAtZero: true,
title: {
display: true,
text: "Sales",
},
},
y: {
beginAtZero: true,
title: {
display: true,
text: "Expenses",
},
},
},
plugins: {
legend: {
position: "top" as const,
},
title: {
display: true,
text: "Monthly Sales vs Expenses Scatter Plot",
},
},
}
return <Scatter data={data} options={options} />
}
export default ScatterChart
Result:
Notes:
- Scatter charts are excellent tools for visualizing the relationship between two variables, allowing for pattern detection and trend analysis.
- The individual points in a scatter chart represent the relationship between the two variables (in this case, sales and expenses) for each time period (in this case, months).
Conclusion
Throughout this guide, you have learned how to visualize complex data in an easily digestible format using various charts in React. We have covered four different chart types: Line, Bar, Doughnut, and Scatter, each serving a unique purpose and providing insights into different aspects of data.
- Line Chart: Demonstrated how to showcase trends over time, such as the monthly sales of different products.
- Bar Chart: Focused on comparing quantities between different categories, like quarterly revenue and expenses.
- Doughnut Chart: Presented a visually appealing way to represent part-to-whole relationships, in this case, monthly sales data.
- Scatter Chart: Taught how to plot two numerical variables against each other to find correlations and patterns, using monthly sales and expenses as an example.
By combining different chart types and customizing them to fit your needs, you can present complex data in a way that's meaningful and actionable.
Top comments (0)