attheoaks.com

Creating Stunning Bar Charts in React Using D3

Written on

Understanding D3.js and React Integration

D3.js is a powerful library that simplifies the integration of graphics into front-end web applications. In this article, we’ll explore how to effectively incorporate D3 to create a bar chart within a React application.

Creating a Bar Chart

To generate a bar chart using D3 in your React app, you'll first need to load your data, set up the axes, and then draw the bars. Here's a sample dataset stored in a CSV file:

year,population

2006,20

2008,25

2010,38

2012,61

2014,43

2016,26

2017,62

Next, in your src/App.js, you can implement the following code:

import React, { useEffect } from "react";

import * as d3 from "d3";

const createBarChart = async () => {

const svg = d3.select("svg"),

margin = 200,

width = svg.attr("width") - margin,

height = svg.attr("height") - margin;

svg

.append("text")

.attr("transform", "translate(100,0)")

.attr("x", 50)

.attr("y", 50)

.attr("font-size", "20px")

.attr("class", "title")

.text("Population Bar Chart");

const x = d3.scaleBand().range([0, width]).padding(0.4),

y = d3.scaleLinear().range([height, 0]);

const g = svg.append("g").attr("transform", "translate(100, 100)");

const data = await d3.csv("data.csv");

x.domain(data.map(d => d.year));

y.domain([0, d3.max(data, d => d.population)]);

g.append("g")

.attr("transform", translate(0, ${height}))

.call(d3.axisBottom(x))

.append("text")

.attr("y", height - 250)

.attr("x", width - 100)

.attr("text-anchor", "end")

.attr("font-size", "18px")

.attr("stroke", "blue")

.text("Year");

g.append("g")

.append("text")

.attr("transform", "rotate(-90)")

.attr("y", 6)

.attr("dy", "-5.1em")

.attr("text-anchor", "end")

.attr("font-size", "18px")

.attr("stroke", "blue")

.text("Population");

g.append("g").call(d3.axisLeft(y));

g.selectAll(".bar")

.data(data)

.enter()

.append("rect")

.attr("class", "bar")

.style("fill", "lightgreen")

.on("mouseover", onMouseOver)

.on("mouseout", onMouseOut)

.attr("x", d => x(d.year))

.attr("y", d => y(d.population))

.attr("width", x.bandwidth())

.transition()

.ease(d3.easeLinear)

.duration(200)

.delay((d, i) => i * 25)

.attr("height", d => height - y(d.population));

function onMouseOver(d) {

d3.select(this).attr("class", "highlight");

d3.select(this)

.transition()

.duration(200)

.attr("width", x.bandwidth() + 5)

.attr("y", d => y(d.population) - 10)

.attr("height", d => height - y(d.population) + 10);

g.append("text")

.attr("class", "val")

.attr("x", () => x(d.year))

.attr("y", () => y(d.value) - 10);

}

function onMouseOut() {

d3.select(this).attr("class", "bar");

d3.select(this)

.transition()

.duration(200)

.attr("width", x.bandwidth())

.attr("y", d => y(d.population))

.attr("height", d => height - y(d.population));

d3.selectAll(".val").remove();

}

};

export default function App() {

useEffect(() => {

createBarChart();

}, []);

return (

<svg width="800" height="600"></svg>

);

}

In this implementation, we define an SVG element in our template. The title for the chart is created using:

svg.append("text")

.attr("transform", "translate(100,0)")

.attr("x", 50)

.attr("y", 50)

.attr("font-size", "20px")

.attr("class", "title")

.text("Population Bar Chart");

The x and y variables are set to establish the ranges for the axes. For example:

const x = d3.scaleBand().range([0, width]).padding(0.4),

y = d3.scaleLinear().range([height, 0]);

The domains for these scales are set based on the data, allowing D3 to dynamically adjust the display based on the data range.

Adding the Axes and Bars

You can create the x-axis using the axisBottom method and the y-axis with axisLeft. The following code snippets illustrate how to add these axes:

g.append("g")

.attr("transform", translate(0, ${height}))

.call(d3.axisBottom(x))

.append("text")

.attr("y", height - 250)

.attr("x", width - 100)

.attr("text-anchor", "end")

.attr("font-size", "18px")

.attr("stroke", "blue")

.text("Year");

For the y-axis:

g.append("g").call(d3.axisLeft(y));

To draw the bars, use the following code:

g.selectAll(".bar")

.data(data)

.enter()

.append("rect")

.attr("class", "bar")

.style("fill", "lightgreen")

.on("mouseover", onMouseOver)

.on("mouseout", onMouseOut)

.attr("x", d => x(d.year))

.attr("y", d => y(d.population))

.attr("width", x.bandwidth())

.transition()

.ease(d3.easeLinear)

.duration(200)

.delay((d, i) => i * 25)

.attr("height", d => height - y(d.population));

This code creates a mouseover event to highlight the bars and show their values.

Conclusion

By leveraging D3.js, you can effectively create bar charts from CSV data in your React applications. If you found this guide helpful, consider subscribing to our YouTube channel for more insightful content!

The first video demonstrates how to integrate D3.js with React to create simple charts, including a bar chart.

The second video provides a straightforward tutorial on creating an easy D3 bar chart.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Crafting Your Ideal Workout Routine: A Comprehensive Guide

Discover how to create and maintain an effective workout routine tailored to your fitness goals.

Free Writing Your Way to Business Success

Discover how free writing can enhance creativity, clarity, and well-being in your entrepreneurial journey.

# Transform Your Life by Celebrating Small Victories

Discover how recognizing small wins can lead to significant personal growth and positive change in your life.