Create Graphs Using D3.JS with React

D3.js is one of the most useful JavaScript libraries to create graphics and charts. React is the most popular frontend web framework. In this blog entry, I would like to touch D3.js library in the React Apps.


Getting started


First, we’ll create a React project using create-react-app:

npx create-react-app d3-app
cd d3-app
npm start
npm i d3



Using D3.js v6 with the React App


We can use D3 in React app by putting the D3 code in the useEffect Hook callback. This is because we’re selecting an element with the DOM and then changing it with D3.

For example, we can write:

import React, { useEffect } from "react";
import * as d3 from "d3";

export default function App() {
  useEffect(() => {
    d3.select(".target").style("stroke-width", 5);
  }, []);
  return (
    <div className="App">
      <svg>
        <circle
          class="target"
          style={{ fill: "green" }}
          stroke="black"
          cx={50}
          cy={50}
          r={40}
        ></circle>
      </svg>
    </div>
  );
}

We get the SVG with the target class and then change the stroke-width after selecting it.


Creating graphs from data


One of the most important use cases for D3 is to create graphs from data. To do so, we can read the data from a CSV.

For example, we can read data from the data.csv file in the src folder:

In App.js, we write:


import React, { useEffect } from "react";
import * as d3 from "d3";
import "d3-time-format";
const parseTime = d3.timeParse("%d-%b-%y");
const createGraph = async () => {
  const margin = { top: 20, right: 20, bottom: 50, left: 70 },
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;
  const x = d3.scaleTime().range([0, width]);
  const y = d3.scaleLinear().range([height, 0]);
  const valueLine = d3.line()
    .x((d) => { return x(d.date); })
    .y((d) => { return y(d.close); });
  const 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})`);
  let data = await d3.csv(require("./data.csv"))
  data.forEach((d) => {
    d.date = parseTime(d.date);
    d.close = +d.close;
  });
  data = data.sort((a, b) => +a.date - +b.date)
  x.domain(d3.extent(data, (d) => { return d.date; }));
  y.domain([0, d3.max(data, (d) => { return d.close; })]);
  svg.append("path")
    .data([data])
    .attr("class", "line")
    .attr("d", valueLine);
  svg.append("g")
    .attr("transform", `translate(0, ${height})`)
    .call(d3.axisBottom(x));
  svg.append("g")
    .call(d3.axisLeft(y));
}
export default function App() {
  useEffect(() => {
    createGraph();
  }, []);
  return (
    <div>
      <style>{
            .line {
            fill: none;
             stroke: steelblue;
            stroke-width: 2px;
          }
      }
      </style>

With this, we’ll see a line instead of a filled shape.


Conclusion


Great. See how easily we can create graphics with D3.js. It works well with React apps and can be integrated with no extra work.


Contact us at bd@agilytics.in for more information.

38 views0 comments

Recent Posts

See All

© agilytics Technologies Pvt Ltd | 2021 | All rights reserved.

  • Whatsapp
  • LinkedIn Social Icon
  • agilytics Technologies
  • RSS Social Icon
  • Wix Facebook page
DIPP.PNG

Email: bd@agilytics.in

Registered Company Address: 

HRC Professional Hub

Indirapuram, Ghaziabad, U.P.- 201 010

INDIA

paritosh.gupta@agilytics.in_BPMark_web_b