D3.js API Functions – Tutorial With Examples

This tutorial explains various D3.js API functions to add features such as data binding, join, load & parse data, interpolation, etc:

D3.js is an open-source JavaScript data visualization library that comprises of various API functions that adds exciting features such as data binding, join, load and parse external data in CSV, XML, and JSON format, manipulating random numbers, interpolation and text formatting, and internationalization along with various functions such as animation, transition, and graphs formation for visualization of data.

You can refer to our earlier tutorials on this d3 series to know more about its features, benefits, and pre-requisites.

API Functions in D3.js

Data Binding With D3.js

In order to create data visualization such as charts & graphs, it is required to bind or join data with a DOM element.

Data can be an array which is a container that contains numerical values of the same types, as displayed below.

var data = [59.5, 17.2, 9.6, 7.6, 5.5, 0.5]

The first step will be of creating an SVG object, in order to have a plane or a framework to build data visualization of external data, the HTML element is selected with d3.select() and append SVG that acts as a canvas by adding attributes such as width and height for the canvas.

var svg = d3.select(HTML element like body or div)
.attr(width, value from variable for width)
.attr(height, value from variable for height)

The next step is the insertion of SVG element ‘g’ which acts like a group that contains other SVG elements.

svg.selectAll ("g")

Further, bind or join data to this SVG shape attached with canvas, using .data(data) function.

svg.selectAll ("g").data(data)

Next step is to bind data to the DOM elements using .enter () method to .data(data) function.

svg.selectAll ("g").data(data).enter()

Further, append SVG shape so that we can attach the shape to the canvas.

svg.selectAll ("g") .data(data).enter().append("g")

An example of Data binding is given below.

<script src="https://d3js.org/d3.v5.min.js"></script>
var infoset = [59.5, 17.2, 9.6, 7.6, 5.5, 0.5]
var span = 500, ceil = 500;
var scalespan = d3.scaleLinear()
.domain([0, d3.max(infoset)])
.range([0, 400]);
var screen = d3.select("body").append("svg")
.attr("width", span)
.attr("height", ceil)
.append("g").attr("transform", "translate(5,20)");
var rule = screen.selectAll("rect")
.attr("width", function(d){ return scalespan(d);})
.attr("height", 20)
.attr("y", function(d, i){ return i*25; })
.attr("fill", "#b3ccff"); 

.attr("y", function(d, i){ return i*25; })
.attr("x", function(d){ return scalespan(d);})
.text(function(d) {return d;})
.attr("fill", "blue").attr("dy",".85em");
Output of Data Binding
Output is captured in graphical form of Coordinates with data binding

In order to bind data, which in our case, is a continent wise population density

var infoset = [59.5, 17.2, 9.6, 7.6, 5.5, 0.5]

The variable screen is assigned to a drawing area by attaching SVG shape to the html element, which is the body in our case.

The variable scale span takes scaleLinear() function with domain and range parameters in order to plot a graph to display values on the scale in a graphical format.

.data (infoset).enter () will help in binding our dataset assigned to a variable Infoset.

Text is appended in order to plot the values against the rectangles of different lengths corresponding to their values in the dataset.

Joining, Load, And Parse Data In D3.js

D3.js can load external data or locally in variables from different types of files and bind this data to DOM elements.

Different formats of data are CSV, JSON, TSV, and XML, whereas d3.csv(), d3.JSON(), d3.tsv(), and d3.xml() are the respective methods provided to load data files in different formats from external sources by sending an http request to the specified url to load files or data of respective formats as well execute the callback function with parsed respective data objects.

Joining, Load and parse data in D3.js
External data in various formats can be displayed as shown above

The syntax to load CSV data file is as given below.

d3.csv (url [, row, callback]);

#1) The first parameter url above is the URL or server path of the csv file which is an external file to be loaded by the d3.csv function. in our case, it is

http://localhost:8080/examples/ movie_published.csv

#2) The Second parameter is optional

#3) The Third parameter is Callback which is a function that can be passed as an argument by another function, making sure specific code get executed until another code has already finished executing for JSON, TSV, and XML formats of the file, function d3.csv is replaced with d3.json, d3.tsv, and d3.xml respectively.

An example to parse external data is given below.

<script src="https://d3js.org/d3.v5.min.js"></script>
d3.csv("movie_published.csv", function(data) {
console.log(data); });
CSV file loaded
d3.csv() will load the CSV file as displayed above.

If opened in Google Chrome browser, click on F12 and the page refresh will display the console log from the code which in our case is console.log (data), which will display values from data set, with column heads, movie_name and year will be displayed from the CSV file kept at the server location.

Manipulating Random Numbers In D3.js

d3 – random API methods return random numbers from various probability distributions, which is a mathematical function, that calculates the chances of occurrences of different outcomes possible.

These functions primarily use the Math. random function of JavaScript that produces numbers that fall between the minimum and a maximum number of the range specified, it results in a unique number every time the Math. random function gets executed.

  • d3.randomUniform – Generate random numbers from a uniform distribution. E.g. d3.randomUniform (1, 2) () – will return random numbers inclusive of 1 and less than 2.
  • d3.randomNormal – Generate random numbers from a normal distribution, E.g. d3.randomNormal (1, 2) () – will return an integer number that is between a specified minimum value and maximum values.
  • d3.randomLogNormal – Generate random numbers from a log-normal distribution, and the expected value will be the natural logarithm value for the random variable.
  • d3.randomBates – Generate random numbers from a Bates distribution, with independent variables.
  • d3.randomIrwinHall – Generate random numbers from an Irwin–Hall distribution.
  • d3.randomExponential – Generate random numbers from an exponential distribution.

Example of Random functions in d3

<title>Random Functions in d3</title>
<script src="https://d3js.org/d3.v5.min.js"></script>
<h3>Random Functions in d3</h3>
document.write(d3.randomUniform(1, 2)() +"<p>");
document.write(d3.randomNormal(1, 2)()+"<p>");
document.write(d3.randomLogNormal(1, 2)()+"<p>");
document.write(d3.randomBates(1, 2)()+"<p>");
document.write(d3.randomIrwinHall(1, 2)()+"<p>");
document.write(d3.randomExponential(1, 2)()+"<p>");
Random Functions in d3
The output of d3 random methods is displayed

Interpolation In D3.js

API methods applied to interpolate between two random values will depend on the type of the ending value b, General syntax is d3.interpolate (a, b). Given below is a table that lists data types of end value b, and corresponding method or function that will change as per the data type.

Type of end value bMethod name used
If b is Boolean, null or undefinedConstant b will be used
If b is a numberinterpolateNumber ( )
If b is a color or string that refer to colorinterpolateRgb( )
If b is a dateinterpolateDate( )
If b is a stringinterpolateString( )
If b is a typed array of numbersinterpolateNumberArray( )
If b is a generic arrayinterpolateArray ( )
If b is referring to numberinterpolateNumber ( )
OtherwiseinterpolateObject ( )

The below example explains:

  • d3.interpolateNumber () function with 10 as start value and end value as 20, values displayed range from start value 10 to end value 20 for interpolate params from (0.0) to (0.5) till (1.0)
  • d3.interpolateRgb () function for two different color names which result in corresponding rgb(‘r’,’g’,’b’) values as a result, for interpolate params from (0.0) to (0.5) till (1.0)
  • d3.interpolateDate() function for two different dates in the format ‘yyyy-mm-dd hh:mm:ss’, will display dates between the above date range, for interpolate params from (0.0) to (1.0)

An example of interpolating for numbers, colors, and dates between the range is given below.

<script src="https://d3js.org/d3.v5.min.js"></script></head>
<h3>Interpolate Numbers, Colors and Dates</h3>
var inpolat = d3.interpolateNumber(99,100);

document.write(inpolat(0.0) + "<p>");
document.write(inpolat(0.2)+ "<p>");
document.write(inpolat(0.5) + "<p>");
document.write(inpolat(1.0)+ "<p>");

var inpolcolrs = d3.interpolateRgb("yellow", "aquamarine");

document.write(inpolcolrs(0.0)+ "<p>");
document.write(inpolcolrs(0.2)+ "<p>");
document.write(inpolcolrs(0.5)+ "<p>");
document.write(inpolcolrs(0.8)+ "<p>");
document.write(inpolcolrs(1.0)+ "<p>");

var inpoldates = d3.interpolateDate(new Date("2020-01-01 00:00:00"), new Date("2020-01-15 23:59:59"));
document.write(inpoldates(0.0)+ "<p>");
document.write(inpoldates(0.2)+ "<p>");
document.write(inpoldates(0.5)+ "<p>");
document.write(inpoldates(0.8)+ "<p>");
document.write(inpoldates(1.0)+ "<p>");
Interpolation in d3
Interpolation in D3.js for Numbers and Colors

Text Formatting And Internationalization With D3.js

Text formatting and Localization can be achieved in D3.js with Number format, Date format, and locale functions as explained below with examples.

D3 – locale ()

d3.locale (definition) , will return locale specific to definition, by default, the locale definition is U.S. English for d3.locale(definition),

The properties for number formatting for the locale definition are listed below.

  • decimal: The decimal point is usually applied in currencies like 25.75 (E.g. “.”).
  • thousands: Thousand is an identifier or a separator that is used as a comma after a thousand values like 2,475 (E.g. “,”).
  • grouping: Group of Array for every group and the size can be checked by using Arrayname[5 ], where 5 is an index and the array size is 6 members.
  • currency: Prefix and suffix for the currency strings (E.g. [“$”, “”]).
  • dateTime:  The date and time (%c) format will have date and time (E.g. “%a %b %e %X %Y”).
  • date: The date (%x) (E.g. “%m/%d/%Y”) format string in Month Day and Year.
  • time: The time (%X) (E.g. “%H:%M:%S”) format string in Hours Minutes and Seconds.
  • periods: The locale’s A.M. and P.M. equivalents (E.g. [“AM”, “PM”]).
  • days: Days of the week, starting with Sunday, in alphabets.
  • shortDays: Short Days or abbreviated names such as SUN, MON, etc of the weekdays, starting with Sunday.
  • months: The month’s full names as October (starting with January).
  • shortMonths: Short Months or abbreviated names such as JAN, FEB, MAR, etc. of the months (starting with January).

All parameters explained above are displayed as variables with their respective values in the following image.

default locale
Default locale is en_US, Russian locale (ru_RU) has Date, Time and Interval constants.


d3.format from JavaScript library takes a number as an input argument, the syntax is d3.format(specifier), in order to transform numbers, d3.format is used.

An example of applying format based on d3 is given below.

<head><title>Formatting for currency</title>
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style type="text/css">
body {padding: 50px; font: 16px Courier;}
p { color:blue; font-size: 16px; font-weight: bold;}</style>
<body><script type="text/javascript">
var body = d3.select("body");
var comafmt = d3.format(","),
decimalfmt = d3.format(".1f"), 
comadecimalfmt = d3.format(",.2f"),
suffixfmt = d3.format("s"),
suffixfmtDecimal1 = d3.format(".1s"),
suffixfmtDecimal2 = d3.format(".2s"),
rupiemoneyfmt = function(d) { return "Rs " + comadecimalfmt(d); },
intmoneyfmt = function(d) { return "$ " + comadecimalfmt(d); },
euromoneyfmt= function(d) { return "€ " + comadecimalfmt(d); },
percentfmt = d3.format(",.2%");

var number = 27500;

body.append("p").text("Number used for formatting is : " + number).style("font-weight", "bold");
body.append("p").text(function() { return 'Indian Rupee format of above Number : ' + rupiemoneyfmt(number); });
body.append("p").text(function() { return 'International Currency format will be : ' + intmoneyfmt(number); });
body.append("p").text(function() { return 'Euro Currency format will be : ' + euromoneyfmt(number); });
body.append("p").text(function() { return 'Percent format : ' + percentfmt(number); });
body.append("p").text(function() { return 'Suffix for large number : ' + suffixfmt(number); });
body.append("p").text(function() { return 'Round off ceil number: ' + suffixfmtDecimal1(number); });
body.append("p").text(function() { return 'Round off floor number : ' + suffixfmtDecimal2(number); });
body.append("p").text(function() { return 'Comma for large number: ' + comafmt(number); });
body.append("p").text(function() { return 'One decimal format : ' + decimalfmt(number); });
body.append("p").text(function() { return 'Two decimal format : ' + comadecimalfmt(number); });
for number and currency
Formatting applied for number and currency using d3.format

Modifying With Date Formats With D3.js

Time formatting using D3.js library, where d3.timeParse can be applied with wild card characters i.e. regular expression that help to convert input time format to the desired format.

An example of the format related to Time and Date is given below.

<head><script src="https://d3js.org/d3.v5.min.js"></script>
<style type="text/css"> body {font-family: Arial, Helvetica, sans-serif; color: blue;}</style>
var datetimefmt = d3.timeFormat('%d-%m-%Y %H:%M:%S %p');
document.write(datetimefmt(new Date()) +"<p>");
var timePortion = d3.timeFormat('%H:%M:%S %p');
document.write(timePortion(new Date()) +"<p>");
var datePortion = d3.timeFormat("%B %d, %Y");
document.write(datePortion(new Date())+"<p>");
var datefmt = d3.timeFormat(" %d");
document.write(datefmt(new Date())+"<p>");
var dayfmt = d3.timeFormat("%A ");
document.write(dayfmt(new Date())+"<p>");
var monfmt = d3.timeFormat("%B");
document.write(monfmt(new Date()) +"<p>");
Date and Time format
Explanation of Date and Time format


In this tutorial, we have covered all the remaining essential methods of D3.js like data binding where data in the form of an array and join, load as well as parse data is in CSV, JSON, and XML format.

We also discussed manipulation using random numbers and interpolate method in order to visualize data groups in charts or graphs, and format text and localization using d3.locale methods for Numbers, date, time, and different locale currencies.