Photo by Stephen Dawson on Unsplash

Beginner Friendly Tutorial to Visualize Data Using React and D3 in 3 steps

Almas Myrzatay
10 min readSep 20, 2022

--

This article will describe how to set up your environment and run React application to visualize data using D3 library. In the previous posts, there was a tutorial on how to set up and visualize data using Python library Plotly. This posts provides an alternative for those who are more familiar with JavaScript and/or are focused on using front-end JS library such as React.

You can check out GitHub page for source code here.

Table of Content

  1. Introduction & Motivation
  2. Python+Plotly vs. React+D3
  3. Step 1 — Environment Set Up
  4. Step 2 — Creating First React Component in JSX
  5. Step 3 — Creating Simple Bar Graph in D3
  6. Conclusion & References

1. Introduction & Motivation

Data visualization is an important concept that spans many (if not all) aspects of our daily lives. Whether one works in the corporate world in the analytics department, customer service, healthcare or research, modern day operations involve data flow.

2. Python+Plotly vs. React+D3

There are many ways to do data visualization. In previous articles, I described a way to visualize data using Python, Pandas and Plotly. In this article, the focus is to display using JavaScript, React and D3 to achieve the same result.

It is also important to highlight the pros/cons of each way. Ultimately, it comes down to your needs and available resources at hand.

JavaScript, React and D3 combo will offer faster way to render data. D3 visualization library is written in 100% in JS, whereas Plotly is written in both Python and JS. In fact, Plotly is built on top of React. Consequently, the visualization code written in Python and Plotly will have to be first converted from Python to JS before displaying, whereas D3 will avoid this transformation in the background. As a result, D3 will be faster when it comes to rendering.

When data is small or number of features on the page is small, the lag is not noticeable, but it will accumulate over time. You don’t want to built a dashboard just to realize that it is not suitable for your needs due to slow processing and rendering.

On the other hand, Python, Pandas, Plotly combo has great statistical tools such as Pandas, ScikitLearn, PyTorch, etc. that make it ideal for data manipulation. Data never comes ready when you import it (from API fetching, web scrapping, etc) and it needs to undergo some sort of pre-processing as well as transformation (grouping, counting, etc). Pandas library in Python, for example, has great out-of-the-box methods that let you work with matrices of many shapes and standards that are supported by many Machine Learning tools such as PyTorch or TensorFlow. Even though, there are some libraries and frameworks in JavaScript that may help with data manipulation, it won’t have the same whistle and bells as Python eco-system.

Here is the link on tutorial on how to do data visualization in Python. In this article, we will present JavaScript solution.

2. Step 1 — Environment Set Up

First step is to create React app, which we will name as data-viz-js. Open source-code editor of your choice (e.g. VSCode), and run the following command with the name of your app in the terminal:

npx create-react-app data-viz-js

Once the local environment is set up, you will need to 1) navigate to your app and 2) start the app inside the terminal

cd data-viz-js
npm start

At this point you should see . If you have never worked with React before, I would recommend official React documentation as a good reference point.

In D3 react library by running following command:

npm install --save react-d3-library

By default you will have initial repo set up that contains package.json, README, src folder, etc. Go ahead into src folder and inside App.js file insert following import statement to import D3 react library into your application:

import rd3 from 'react-d3-library'

Note that since we are in the debug mode, every time you make a change, it will automatically re-render the page, which will eliminate the need to rerun every time new change is introduced into code. For more info about D3 library in React, follow the official doc as a starting point.

Since debug mode is activated by default in React, ensure your code compiles successfully. Below screenshot illustrates where the code has been deployed.

At this point we are ready to begin editing source code to create the dashboard to visualize data.

4. Step 2 — Creating First React Component in JSX

When you create React app and run npm start, you will see standard code in the App.js file that is displayed on the web browser. Let’s clear the code and organize for our use case.

Here is the link to GitHub for ease of copy/paste.

Create dummy data and put it inside the BarGraphSimpleData.js file provided below:

const BAR_GRAPH_SIMPLE_DATA = [{ label: "headphones", value: 100 },{ label: "laptop", value: 600 },{ label: "screen", value: 300 },{ label: "keyboard", value: 50 },];
export default BAR_GRAPH_SIMPLE_DATA;

Now, create new file called BarGraphSimple.js and paste the following code:

const BarGraphSimple = ({ data }) => {return (<p> Graph goes here </p>
)
}
export default BarGraphSimple

Lastly, navigate to App.js folder and import above to files that will host both data and future graph to be rendered on the main page. Here is the link to GitHub for ease of copy/paste.

Let’s break down the code above:

Lines 1–3: Import statements where we import .css styling file, bar graph component and dummy data we created

Lines 5–14: We are rendering H1 style header on the page with the title, and BarGraphSimple component that takes in a data as an input and will render the graph that we provide.

Line 16: exporting App component into consumption by another component elsewhere. In this case, by index.js file

Not very exciting, but at this point, you know how to insert elements in the JSX — a syntax extension for JavaScript. For more info about JSX, you can start in the official React docs.

As next step, we will replace <p> element with D3 graph to visualize dummy data.

5. Step 3—Creating Simple Bar Graph in D3

In this section we will primarily work in BarGraphSimple.js file. Let’s break down graph creation into three parts: set up (1), axis creation (2) and data ingestion (3).

1. Bar graph set up

At the top of the document, after import statements, define the canvas within which bar graph will be shown and how big it will be. In our case, I want it to be displayed in the middle of the page and define width=500 and height=500 minus our margins to center it.

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

Now we will place our graph element on the page. However, in order to work with D3 components, first lesson should be to understand what <svg> is and how it works, at least on surface level. In a nutshell, SVG is 2D vector graphic, which means visual graphics are “created directly from geometric shapes defined on a (Cartesian) coordinate system”. [1]

Vector Graphic vs. Raster Graphic. Image from wikipedia [1]

As an example, bar graph is just a collection of rectangles on a page where each corner is a point on a coordinate system (where entire plane of the system is the webpage you see). So, when you open a webpage, D3 will treat top-left corner as coordinate x=0 and y=0, and top-right corner will be x=page-width and y=0

As we understand <svg>, we need to place it the context of our page we defined earlier.

In the code snippet above, we inserted svg element to be rendered on the webpage. At this point, you won’t see anything on the front end, but we got an element where graph will be located.

Now, create a scale function, which will convert our data points into pixels on screen. For example, based on our sample set, list of values is [100, 600, 300, 50], which will we call domain. And let’s suppose our range is 0–500 pixels. This scale function will transform domain values into consistent pixel value on the screen given the range.

Refer to line 55, where we set y-axis of our graph. We make it a linear scale where domain is between 0 and our highest dataset value (e.g. 600), which will be in range of 500px to 0px.

Line 54 is for our x-axis, which will display labels of our dataset and map them equidistant from each other along the width (500px) we specified on the page.

Remember, scaleX and scaleY are functions that will take our data points as an input and map them to pixels on the page at a coordinate we want.

2. Creating Axis

Let’s create x-axis and y-axis of the graph. Code snippet below shows component CreateAxis, which takes in 3 parameters: axisDirection (e.g. axisBottom, axisLeft functions), scale function (x scale or y scale we defined in prev section), and styling element of transforming.

Let’s break down function below:

Note that since we are writing component as a function, we will use hooks useEffect and useRef.

Line 9: Create variable ref that will hold <g> SVG container element (i.e. our axis). In this case, ref value is set to null at first, but in subsequent renders, it will remember and hold<g> component

Line 17: Return newly created axis, which could be either x-axis or y-axis

Line 11–15: Use hook useEffect that will run every time scale changes. Note specifically line 15, which contains dependency variable scale, which triggers code inside useEffect. This way, whenever scale changes, this component will update without manual intervention.

Now, we will need to add into component BarGraphSimple newly created axis creation component CreateAxis. In code, it will look like this:

The result will look like this:

Note how bottom axis contains transformation of translating the element. If you remove it, the a-axis will appear at the top where tick 600 is located. Recall that top-left of the page has coordinates of (0,0). As a result, we need to translate it to make it at the bottom where tick 0 is located.

3. Data Ingestion

Last part is to ingest data into the graph. Refer code snippet below and let’s break it line by line:

Lines 23–24: Iterate across dummy dataset extracting label and value. Now, recall that we said graph is nothing but collection of SVG elements. In this case, we are defining <rect> elements where we define width, height and color of the rectangle element.

Lines 26–27: We also define x and y scale function that takes as an input data we are iterating thru that we got in line 23.

Line 21: Note that entire body of the function is encapsulated in the return statement.

Here is the link to GitHub for ease of copy/paste.

Now, update BarGraphSimple component to include CreateBars component and pass data, height, and scales as parameters.

The final result on the webpage will look like this:

6. Conclusion and References

In this article we learned how to setup React environment and creating first elements in JSX. Then, we used D3 library to create simple bar graph and displayed it using dummy data we generated.

Even though we did simple graph, there are many more graphs that could be plotted using D3 such as maps (cartograms, choropleth, etc), flow diagrams (Sankey, network, etc) and many more. Explore D3 library for each category here.

References

[1] Vector Graphics. Wikipedia. URL: https://en.wikipedia.org/wiki/Vector_graphics

[2] Golawski, R. (2021). URL: https://dev.to/rgolawski/simple-bar-chart-with-react-and-d3-443p

Thanks for reading my article!

Check out my other stories and make sure to follow me for more beginner friendly tech content!

If you liked it, or have any comments/questions, let me know! Feel free to connect on social media: Instagram, LinkedIn

--

--

Almas Myrzatay

Senior Product Eng @ Axle (YC 22) | ex-Microsoft SWE