D3 Basics. How to create a Bar chart

Artem Diashkin
Oct 14, 2020 · 7 min read

This article will cover the basics of the D3 library, with step-by-step guide of Bar chart implementation.

What will be covered in this article:

  • Prerequisites
  • What we will be implementing?
  • What is SVG?
  • What is D3?
  • D3 DOM manipulations
  • How to create a Bar chart step-by-step:
  • Step 1. Creating SVG element
  • Step 2. Adding JSON data to the project
  • Step 3. Fetching data
  • Step 4. Adding Y-axis
  • Step 5. Adding X-axis
  • Step 6. Modifying X-Axis text label styles
  • Step 7. Adding animated bars to the chart
  • Step 8. Adding labels to the bars

Prerequisites

For this article, you will not need any third-party libraries/frameworks as React.js/Angular/Vue, etc. We will be using a simple static HTML page for our demos.

For each example, I will attach a code sandbox link.

What we will be implementing?

Before I will start telling you about the basics of the D3 library, you can check what you will get as a result:

What is SVG?

Scalable Vector Graphics (SVG) is an XML-based markup language for describing two-dimensional based vector graphics. As such, it’s a text-based, open Web standard for describing images that can be rendered cleanly at any size and are designed specifically to work well with other web standards including CSS, DOM, JavaScript, and SMIL. SVG is, essentially, to graphics what HTML is to text.

SVG graphics consists of basic shapes:

  • Rectangle → <rect … />
  • Circle → <circle… />
  • Ellipse → <elipse… />
  • Line → <line… />
  • Polyline → <polyline… />
  • Polygon → <polygon… />
  • … and the most powerful one, Path → <path… />

Let’s take a look at simple SVG examples:

SVG Path example:

What is D3 ?

D3 Data Driven Documents)(or D3.js) is a JavaScript library for visualizing data using web standards. D3 helps you bring data to life using SVG, Canvas, and HTML. D3 combines powerful visualization and interaction techniques with a data-driven approach to DOM manipulation, giving you the full capabilities of modern browsers and the freedom to design the right visual interface for your data.

If you are using a simple HTML static page, you can add the D3 library by adding this line directly into your HTML page:

<script src="https://d3js.org/d3.v6.min.js"></script>

Or, you can add it with the use of npm (if you are using React.js or similar):

If you are working on a Typescript project, don’t forget to add types for D3:

D3 DOM manipulations

Most of the time you will need to use d3-selection module (it is just like the document.getElementBy…) that will allow us to manipulate the DOM tree.

Let’s tale a look at a simple D3 example where we will select and element and “append”/”add” a new one as a child element:

As you can see we can add elements, style, attributes, even HTML fragments into the DOM with the use of the D3 library.

If you want to get some cool D3 examples, you can check them here:

How to create a Bar chart step-by-step

Step 1. Creating SVG element

Let’s start with a simple step.

First, we should get our div element by id='svg-container'., and attach a new svg element to it with few attributes — height, width, and margins.

You can adjust all those values in the future, depending on the amount of data rows, texts, labels, etc…

After running this script you will not see anything on the screen, but you can find SVG element in the dev tools window:

If you would like to know more about D3 Margin Convention , you can check them here:

Step 2. Adding JSON data to the project

Next, we will need to add a JSON file with chart data into a project. You can add any data you want with any names and values, with only one restriction → names/keys should be unique.

Step 3. Fetching data

To fetch data from a server (or a local file, in our case) we will need to use d3-fecth module. Don’t worry, no additional imports 😉

We will need to add d3.json function and pass a URL prop, that will return a Promise (line 16):

Our data will be automatically converted to JS Array with objects, so we don’t need to use JSON.parse or something similar, D3 will do that for us automatically:

Step 4. Adding Y-axis

Now it is time to add our first Y-Axis chart element.

I have commented previously added code for preventing a mess in a code snippet. I’m showing only the “Step 4" code:

Result:

What are domain ,range and nice?

Domain → values that will be added to the chart (from min to max). D3 library provides a function max() that will find a maximum value in the array

Range — Y-axis size. You can think of it as a y-axis starting point.

Example: If we will set hard-coded values to the range and domain...

let y = d3.scaleLinear().range([HEIGHT, 400]);function createAxisLeft(data) {
y.domain([0, 2000]).nice();
...
}

we will get this:

Step 5. Adding X-axis

Now, let’s add X-axis mainly the same way as we did with Y-axis:

Result:

Step 6. Modifying X-Axis text label styles

What if we would want to rotate our text by 90 degrees. Let’s add a function for that:

Result:

Step 7. Adding animated bars to the chart

Now, the most interesting part, I think → adding bars with animation 😉

Result:

I think that we need to talk I little about these lines of code:

All you need to know is the enter() function.

First, we are selecting all elements with class names .bars . Hm, but we didn’t create such elements previously. By enter() function will create those if it wasn’t found (for each element in “data” array, six, in our case):

And after that, we are population those six groups with SVG rectangles at line 17:

Step 8. Adding labels to the bars

Mostly the same as we did with bars. Here we are specifying x and y coordinates and text position of the labels:

Now, our D3 chart is ready:

You can use this Codesandbox project as your playground, happy coding:

Next time I will show you how we can use D3 library in the React.js projects. Both D3 and React.js, are libraries that are manipulating DOM, so it can be “painful” to use them both at the same time. If you are in a hurry, you can check more about it here:

LITSLINK Frontend Development

Your go-to place for frontend dev trends, know-hows, hacks and tricks.

Artem Diashkin

Written by

Java, Spring, Node.js, AdonisJs, React.js and Flutter developer

LITSLINK Frontend Development

Frontend development is key to user’s happiness & satisfaction. Read how Litslink’s engineering team is solving the hardest FE challenges for the most admirable startups in 2021.

Artem Diashkin

Written by

Java, Spring, Node.js, AdonisJs, React.js and Flutter developer

LITSLINK Frontend Development

Frontend development is key to user’s happiness & satisfaction. Read how Litslink’s engineering team is solving the hardest FE challenges for the most admirable startups in 2021.

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store