Create Line Chart with D3 and React

Paul Ho
3 min readOct 30, 2021

Visual representations of data are the most effective means of conveying meaningful information

What is D3 ?

D3 stands for Data-Driven Documents. It is an open-source JavaScript library to create custom interactive data visualizations in the web browser using SVG, HTML and CSS.

D3 allows you to bind arbitrary data to a Document Object Model (DOM), and then apply data-driven transformations to the document

Create React App

Create a React project using create-react-app,

npx create-react-app react-d3-linechart
cd react-d3-linechart

Install D3

Install D3.js package,

npm i d3

Replace App.js

Replace App.js in src directory with following code, we will use the Effect Hook and import D3 package,

import React, { useEffect } from "react";
import * as d3 from "d3";
function App() {
useEffect(() => {
}, []); return (
<>
</>
);
}
export default App

Create createGraph() function

Let’s create an empty createGraph() function and it is ready to be called by Effect Hook,

import React, { useEffect } from "react";
import * as d3 from "d3";
function App() { const createGraph = async () => {
}
useEffect(() => {
createGraph();
}, []);
return (
<>
</>
);
}
export default App

Read data from CSV

We will get the csv data from https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/3_TwoNumOrdered_comma.csv

The csv made up of two columns, date and value,

const createGraph = async () => {    // read from csv and format variables
let data = await d3.csv('https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/3_TwoNumOrdered_comma.csv')
let parseTime = d3.timeParse("%Y-%m-%d");
data.forEach((d) => {
d.date = parseTime(d.date);
d.value = +d.value;
});
console.log(data)
}

At this point of time, you can check the data from JavaScript console log after running the React application, using the following command

npm start

Append the SVG object

We will append the SVG object to the body of the page by setting the dimensions and margins of the graph,

const createGraph = async () => {    ...    // set the dimensions and margins of the graph
var margin = { top: 20, right: 20, bottom: 50, left: 70 },
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// append the svg object to the body of the page
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`);
}

Add X axis and Y axis

We will use two D3 scaling methods, d3.scaleLinear() and d3.scaleTime() to draw X axis and Y axis respectively,

const createGraph = async () => {   ...   // Add X axis and Y axis
var x = d3.scaleTime().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
x.domain(d3.extent(data, (d) => { return d.date; }));
y.domain([0, d3.max(data, (d) => { return d.value; })]);
svg.append("g")
.attr("transform", `translate(0, ${height})`)
.call(d3.axisBottom(x));
svg.append("g")
.call(d3.axisLeft(y));
}

Run the application, you should see the X axis and Y axis on graph,

Add the Line

Create the line by append SVG path element with attributes,

const createGraph = async () => {    ...    // add the Line
var valueLine = d3.line()
.x((d) => { return x(d.date); })
.y((d) => { return y(d.value); });
svg.append("path")
.data([data])
.attr("class", "line")
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 1.5)
.attr("d", valueLine)
}

Run the application again, now you see the perfect Line Chart above.

That’s it. You can view the real demo and the source code is available at github.

Thanks for reading.

--

--