D3.js for Data visualization

Dipankar Mazumdar
6 min readJun 11, 2022

In my last blog, I shared some perspectives on whether you should code or use off-the-shelf tools such as Tableau for Data visualization. If you are interested to read it, below is the article.

It is a no-brainer that if our motivation is building a custom or completely new visual representation, programming 🧑🏻‍💻 is the way forward. We also established that to date JavaScript as a programming language has seen huge momentum in building from-scratch visual metaphors. Although JavaScript has no native implementations, particularly around visualizations, it’s the DOM manipulation functions & image formats such as SVG that help you render shapes in the browser.

Now, D3.js has been leveraged in a lot of areas — be it for explaining Machine Learning algorithms, Visualization research, or integration with BI tools(Qlik, Tableau) to present data in interesting ways. For e.g. you can see in the below GIF how intuitively this website uses D3.js-based visuals to introduce Machine Learning to newbies.

ML explained using D3 visuals

Amazing, isn’t it?

Today, as a stepping stone, we will look into some of the key concepts within D3.js and try to understand them. In our next series of blogs, we will focus on building a new visualization using the concepts we develop today. Typically, people consider (and I agree🤷🏻‍♂️) that there is a learning curve to implementing D3 and through this blog series we will try to simplify it.

SVG — Scalable Vector Graphics 🎨

SVG is the core of D3.js. It is an XML-based vector graphics image format that lets you draw various shapes such as rectangles, circles, etc. A simple SVG markup may look like the below -

<svg width="500" height="80">
<rect x="0" y="0" width="50" height="50" fill="orange"></rect>
</svg>

As you can see in this example, we have used a predefined SVG shape <rect>. Now, this SVG placed inside an HTML would look something like this. As simple as that.

<rect> rendered in browser

Other predefined SVG shapes are -

  • Rectangle <rect>
  • Circle <circle>
  • Ellipse <ellipse>
  • Line <line>
  • Polyline <polyline>
  • Polygon <polygon>
  • Path <path>

Selection API 👉🏻

Selection is another non-trivial concept in the D3 world. Its purpose is to allow you to select elements on your web page so you can manipulate the DOM elements. For instance, you can do something simple like below where you select a <div> tag and style it to be green color on your HTML page.

<body>
<div class = "first_div">
Hello D3!
</div>

<script>
d3.select(".first_div").style("color", "green");
</script>
</body>
Output for the above Select code

D3 allows for DOM element selections using the two methods:

  • select() — select only one element based on the criteria
  • selectAll() — select all DOM elements based on the criteria

Binding Data 📈

Okay, so you have a high-level understanding of what SVG is and how you can play around with the DOM elements using select methods. Now, the next step is to understand how you can bind your data to the visual representation.

Imagine you have the following dataset.

How do you bind this data to build a rectangle for each element of these elements & represent it as a Bar chart?

This is where the data() method comes into play. It is used to bind the array of data to the selected DOM element. D3 supports a variety of data formats such as an array, CSV, JSON, and TSV files.

var bars= svg.selectAll("mybar")
.data(data)
bars.enter().append("rect")
.attr("x", function(d) { return x(d.Country); })
.attr("y", function(d) { return y(d.Value); })
.attr("width", 20)
.attr("height", function(d) { return height - y(d.Value); })
.attr("fill", "#69b3a2");

As you can see from the above snippet, we joined our dataset to the svg using data() and the d3.append() method adds a ‘rect’ SVG for each of the element.

Output of binding data

Scales API 📐

Mike Bostock, the creator of D3.js defines scales as “functions that map from an input domain to an output range”. Scales control how we visually percept data in the projection space. In a real-world scenario, the values that you have in your dataset will probably not match the pixel values on the screen. For instance, take a look at this array —


var data =[100, 400, 300, 900, 850, 1000]

If you have to map these data values exactly to the pixel values on the screen, you can’t possibly do that as the values are too large. So, you will need to bring them to a certain scale. D3 provides methods to transform data into specific scales. E.g. scaleLinear(), scaleLog().

Note that each scale needs to be defined with a domain and range.

Domain: represents the minimum and maximum values of your input data

Range: represents the values our output data will lie within

Read more on scales below.

Transformation ℺

When dealing with charts on a web page, you may want to transform one or more SVG elements to align them as per your requirements. For E.g. you may want to move a rectangle that you have drawn from its default position or rotate it. A horizontal bar chart is a typical example where the rectangles are rotated horizontally.

D3.js provides an attribute transform to do so and you can use one or more of the following values — translate, rotate, scale & skew.

var svg4 = d3.select("#barnew3").append("svg")
.attr("width", 320)
.attr("height", 220)
.append("g")
.attr("transform",
"translate(" + 15 + "," + 60 + ")");

The snippet above shows an example where we rotate our bar chart horizontally.

A bar chart rotated horizontally

Animations 🦊

Animations are a key aspect of D3.js charts. They provide certain meaning to storytelling and enable user interaction and allow for better exploration. Bar race charts are a common example of leveraging animations.

A Bar race chart in D3

Animations in D3 are supported via transitions on DOM-selected elements. To start a transition, d3.selection.transition() method is used and then you can use the various transition methods to build up your animation. Some of the common methods are — duration(), ease() & delay().

I created a simple donut chart below that uses the ease() method to highlight the chart’s arcs when hovered over.

function update(){
donut.transition()
.attr("stroke","black")
.attr("stroke-width",5);
}

This brings us to the end of this article. We went over a few building blocks that would help you understand the core concepts behind D3.js and hopefully, it will serve as a reference for anyone starting with D3.

Created a new visualization using D3.js? Share with me on my social.

Twitter: https://twitter.com/Dipankartnt

LinkedIn: https://www.linkedin.com/in/dipankar-mazumdar/

~Dipankar

--

--

Dipankar Mazumdar

Dipankar is currently a Staff Data Engineering Advocate at Onehouse.ai where he focuses on open source projects in the data lakehouse space.