DEV Community

John Au-Yeung
John Au-Yeung

Posted on • Originally published at thewebdev.info on

Adding Graphics to a React App with D3 — Line Graph

Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62

Subscribe to my email list now at http://jauyeung.net/subscribe/

D3 lets us add graphics to a front-end web app easily.

Vue is a popular front end web framework.

They work great together. In this article, we’ll look at how to add graphics to a Vue app with D3.

Line Graph

We can add a line graph into our React app with D3.

To do this, we write:

public/data.csv

year,population
2006,20
2008,25
2010,38
2012,41
2014,53
2016,26
2017,42

Enter fullscreen mode Exit fullscreen mode

App.js

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

const createLineChart = async () => {
  const margin = { top: 20, right: 20, bottom: 30, left: 50 },
    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(function (d) {
      return x(d.year);
    })
    .y(function (d) {
      return y(d.population);
    });

  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})`);

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

  data.forEach(function (d) {
    d.population = +d.population;
  });

  x.domain(
    d3.extent(data, function (d) {
      return d.year;
    })
  );

  y.domain([
    0,
    d3.max(data, function (d) {
      return d.population;
    })
  ]);

  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(() => {
    createLineChart();
  }, []);

  return (
    <div className="App">
      <style>{`
        .line {
          fill: none;
          stroke: green;
          stroke-width: 5px;
        }
      `}</style>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

We create the createLineChart function to create the line chart.

First, we write:

const margin = {
    top: 20,
    right: 20,
    bottom: 30,
    left: 50
  },
  width = 960 - margin.left - margin.right,
  height = 500 - margin.top - margin.bottom;

Enter fullscreen mode Exit fullscreen mode

to set the margins, width, and height of the chart.

Then we add the x and y objects to let us add the min and max values for the lines:

const x = d3.scaleTime().range([0, width]);
const y = d3.scaleLinear().range([height, 0])

Enter fullscreen mode Exit fullscreen mode

Then we set the data for the x and y axes:

const valueline = d3
  .line()
  .x(function(d) {
    return x(d.year);
  })
  .y(function(d) {
    return y(d.population);
  });

Enter fullscreen mode Exit fullscreen mode

Next, we add the svg element into our component with:

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})`);

Enter fullscreen mode Exit fullscreen mode

Then we read the data from the CSV with:

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

Enter fullscreen mode Exit fullscreen mode

Then we add the x and y domains with:

data.forEach(function(d) {
  d.population = +d.population;
});

x.domain(
  d3.extent(data, function(d) {
    return d.year;
  })
);

y.domain([
  0,
  d3.max(data, function(d) {
    return d.population;
  })
]);

Enter fullscreen mode Exit fullscreen mode

to return the labels for the x and y axes.

To add the line, we write:

svg.append("path").data([data]).attr("class", "line").attr("d", valueline);

Enter fullscreen mode Exit fullscreen mode

We add the x-axis with:

svg
  .append("g")
  .attr("transform", `translate(0, ${height})`)
  .call(d3.axisBottom(x));

Enter fullscreen mode Exit fullscreen mode

And we add the y-axis with:

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

Enter fullscreen mode Exit fullscreen mode

Conclusion

We can add a line graph with D3 into our React app.

The post Adding Graphics to a React App with D3 — Line Graph appeared first on The Web Dev.

Top comments (0)