0% found this document useful (0 votes)
122 views1 page

Data Visualization With D3.js. This Blog Deals With Visualization of - by Ankit Agarwal - Medium

This document discusses using D3.js to visualize data. It provides an overview of key concepts needed for D3 including HTML, DOM, CSS, SVG, and JavaScript. It then demonstrates how to install D3, select and add elements to the DOM, bind data to elements, and create a basic bar chart visualization. References are provided at the end to help learn these necessary technologies.

Uploaded by

Bleep News
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
122 views1 page

Data Visualization With D3.js. This Blog Deals With Visualization of - by Ankit Agarwal - Medium

This document discusses using D3.js to visualize data. It provides an overview of key concepts needed for D3 including HTML, DOM, CSS, SVG, and JavaScript. It then demonstrates how to install D3, select and add elements to the DOM, bind data to elements, and create a basic bar chart visualization. References are provided at the end to help learn these necessary technologies.

Uploaded by

Bleep News
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Ankit Agarwal 5 Followers About Follow Sign in Get started

Data Visualization with D3.js


Ankit Agarwal Nov 18, 2019 · 8 min read

This blog deals with visualization of data with the help of D3.js. It is the
second blog in continuation of my last blog, which provides basic idea of
Data Science Life-cycle.

Here is the first blog.

D3 stands for Data-Driven Documents. It is an open source JavaScript


library for manipulating DOM elements. D3 helps you bring data to life
using HTML, SVG, and CSS.
Diving into D3 requires knowledge of following concepts, let’s catch them
all in brief:

HTML — Hypertext Markup Language (HTML) is used to create web


pages and web applications. A simple HTML page look like:

DOM — A Web page is a document. The Document Object Model


(DOM) is a programming interface for HTML and XML documents. It
represents the page so that programs can change the document
structure, style, and content. The DOM represents the document as
nodes and objects. web browsers parse the DOM in order to make sense
of a page’s content. A DOM of the Mozilla JS documentation(
https://developer.mozilla.org/en-US/docs/Web/JavaScript) looks like:

CSS — Cascading Style Sheets (CSS) is a stylesheet language used to


describe the presentation of a document written in HTML or
XML(including XML dialects such as SVG, MathML or XHTML). CSS
describes how elements should be rendered on screen, on paper, in
speech, or on other media. A simple illustrative example can be:

JavaScript — JavaScript (JS) is a lightweight, interpreted, or just-in-


time compiled programming language with first-class functions. While it
is most well-known as the scripting language for Web pages, many non
browser environments also use it, such as Node.js, Apache CouchDB and
Adobe Acrobat. Providing a basic example here can become bit
overwhelming, so I would rather not 👽

SVG — Scalable Vector Graphics (SVG) is used to define graphics for the
Web. SVG is a text-based image format. Meaning, you can specify what
an SVG image should look like by writing simple markup code, sort of
like HTML tags. In fact, SVG code can be included directly within any
HTML document. A basic example can be:

Since you have shown good amount of patience, I will attach all reference
links at the end 👼

Let’s ride the Roller coaster now.

Installation of D3.js
For NPM use npm install d3. For Yarn use yarn add d3. Otherwise,
download the latest release or load it directly from d3js.org.

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

When using D3 in an environment that supports ES modules, you can


import the default D3 bundle as a namespace

import * as d3 from "d3";

Few words of caution : We are extensively going to use HTML,SVG, CSS and
JavaScript along with D3. Also, method chaining would play a crucial role.
Kindly get yourself familiar with all of these. To help you, References are
attached at the end.
(…) represents any parameter in method in the coming sections

Selection/ addition of elements:


D3 can be used to create a new DOM element. We’ll start simple, and just
create a <p> paragraph element.

Let’s start by taking simple HTML template:

Run the file and you will see nothing in browser. Now append the following
code under script tag in body

Save and refresh, and voila! There is text “New paragraph by D3!”in the
formerly empty browser window.

Let’s decode what just happened here, magic ? of course not. Each method
can be explained as:

1. select(…) — D3’s select method selects a single element from the DOM
using CSS selector syntax. (We selected the body.)

2. append(…) — This method creats a new element and append that to the
end of our selection, we appended <p> just before the closing </body>
tag in this case.

3. text(…) — It sets the text content of that new, empty paragraph to “New
paragraph by D3!”

Data binding:
In D3, we can bind our data input values to elements in the DOM and can
create new elements based on our data.

Let’s just replace script tag content of last example with the following:

Run the HTML file and the output would be:

Let’s understand what happened here:

1. select(…) — Finds the body in the DOM and hands a reference off to the
next step in the chain..

2. selectAll(…) — Selects all paragraphs in the DOM. Since none exist yet,
this returns an empty selection.

3. data(…) — Counts and parses our data values. There are five values in
our data set, so everything past this point is executed five times, once for
each value.

4. enter(…) — To create new, data-bound elements, you must use enter().


This method looks at the DOM, and then at the data being handed to it. If
there are more data values than corresponding DOM elements, then enter()
creates a new placeholder element on which you may work your magic.

5. append(…) — Takes the placeholder selection created by enter() and


inserts a <p>element into the DOM. Hooray! Then it hands off a reference
to the element it just created to the next step in the chain.

6. text(…) — Takes the reference to the newly created <p>and inserts a


text value.

7. style(…) — Takes the reference to the newly created <p>and use css
property on selections using a custom function.

Data visuals:
Bored, maybe yes/ maybe no 😁 Let’s do some drawing.

We are going to build simple bar chart. To display bar we can simply use div
of HTML with few properties of css :

Let’s now replace content of our favorite script tag as follows:

The result in the browser will look like :

After seeing this, You must be saying Wow, What a beautiful piece of Art 😉

Want to decode methods listed in the code. We are already familiar with
most methods. Let’see what else we got here:

1. attr(…) — attr is used to set and HTML attribute and its value on an
element. In the example we used attr to select(/to create) div with class bar.

2. style(…) — As described earlier, here we are changing height of div


elements based on data set.

The final showdown — SVG with transitions:


D3 is most useful when used to generate and manipulate visuals as SVGs.

So let’s dip to the bottom with the coaster now.

In this example we are going to build bar chart with transitions to show the
data in more appealing way. Now try to maintain your pace with below
code snippets and their explanations.

1. Loading the data set :

It is a simple JS object of XYZ company with sales data at the end of first six
months.

2. Setting up SVG playground

A SVG container of size 500*400 with margins to plot bar chart properly.

3. Setting scales and axis for the chart

Let’s check out each function here

d3.scale.liner(…) — a linear scale which transforms data values to visual


variables. domin(…) takes input between [0,10] and range() maps it
between [350,0]

(we are considering Y scale, and calculated numbers based on our dataset)

rangeRoundBands(…) — arranges our bars in graceful way.

d3.svg.axis(…) — creates new default axis.

scale(…) — sets the scale on axis (default is liner scale)

orient(…) — sets the orientation of axis (default is bottom)

ticks(…) — takes any number, but it will modify that number to make sure
the axis is a multiple of 2, 5, or 10.

4. Calculating bar height and calculating year labels in DD/MM format

calcBarName(…) — custom function to calculate date labels in DD/MM


format

calcBarHeight(…) — custom function to calculate bar height using yScale.

5. Setting up SVG container and bars

We have already covered methods listed here. “g” element under append is
used to group svg shapes together.

attr(“transform”,”translate(tx,ty)”) — we are using transformation


(movement/rotation or skew)here. translate takes two options, tx refers
translation along the x-axis and ty refers to the translation along the y-axis.

6. Setting the transition in bars

we are setting transitions in bars which will happen in 3000 ms duration.

7. Adding axis to the chart

here we are adding axis to the chart. The methods used here are already
covered.

Curious about the result of this exercise, check the following link and try
out your own experiments with the code:

https://jsfiddle.net/ankit1ag/0Lpbksgd/

https://jsfiddle.net/ankit1ag/0Lpbksgd/

A true developer never breaks his promises. Brace yourselves with the help
of following links:

HTML: Hypertext Markup Language


HTML (HyperText Markup Language) is the most basic building
block of the Web. It defines the meaning and structure of…
developer.mozilla.org

CSS: Cascading Style Sheets


Cascading Style Sheets ( CSS) is a stylesheet language used to
describe the presentation of a document written in HTML…
developer.mozilla.org

JavaScript
JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled
programming language with first-class…
developer.mozilla.org

D3.js - Data-Driven Documents


D3 is a JavaScript library for visualizing data with HTML, SVG, and
CSS.
d3js.org

SVG Tutorial
SVG stands for Scalable Vector Graphics. SVG defines vector-based
graphics in XML format. With our "Try it Yourself"…
www.w3schools.com

Method chaining
Method chaining, also known as named parameter idiom, is a
common syntax for invoking multiple method calls in…
en.wikipedia.org

So now, you are familiar with basic methods of D3.js and can draw some
basic bar charts using D3.js — but there’s so much more to learn. Follow the
above links to get more knowledge about it. I hope this tutorial shed some
light on D3

To all my riders, ride ends here, how was it, did you like it?

you can write your comments here or can connect with me at LinkedIn. I’d
love to hear from you.
ABC. Always be clappin’.

JavaScript Framework Data Visualization Developer D3js

More from Ankit Agarwal Follow

Full Stack Developer | ML & Data Science Enthusiast

More From Medium

JavaScript and Building Content-Rich The Best and Most Vue From The TOP — Vue
Accessibility: Don’t Blame Pages on React Native Different Way to Create CLI 3
the Language Vanya Deasy Safrina in
Styles in React Apps Vamshi Krishna in My Point of
Myplanet in Myplanet Musings Traveloka Engineering
using JSS and TypeScript Vue
Omid Shah Hosseini in Weekly
Webtips

Angular 8 — Automatic Creating a REST API with Javascript Methods Learn React, Redux and
application refresh on NestJS — Part 04 — Quick Shuvo Das
Typescript in 2021 —
user’s side Adding a Dockerfile with Shopping Cart Example -
Julien Schneider
Reduced Image Size Cart Implementation #4
Marcos Henrique da Silva in Wojciech Bilicki
JavaScript in Plain English

About Write Help Legal

You might also like