D3.js – Geographies

D3.js – Geographies ”; Previous Next Geospatial coordinates are often used for weather or population data. D3.js gives us three tools for geographic data − Paths − They produce the final pixels. Projections − They turn sphere coordinates into Cartesian coordinates and Streams − They speed things up. Before learning what geographies in D3.js are, we should understand the following two terms − D3 Geo Path and Projections Let us discuss these two terms in detail. D3 Geo Path It is a geographic path generator. GeoJSON generates SVG path data string or renders the path to a Canvas. A Canvas is recommended for dynamic or interactive projections to improve performance. To generate a D3 Geo Path Data Generator, you can call the following function. d3.geo.path() Here, the d3.geo.path() path generator function allows us to select which Map Projection we want to use for the translation from Geo Coordinates to Cartesian Coordinates. For example, if we want to show the map details of India, we can define a path as shown below. var path = d3.geo.path() svg.append(“path”) .attr(“d”, path(states)) Projections Projections transform spherical polygonal geometry to planar polygonal geometry. D3 provides the following projection implementations. Azimuthal − Azimuthal projections project the sphere directly onto a plane. Composite − Composite consists of several projections that are composed into a single display. Conic − Projects the sphere onto a cone and then unroll the cone onto the plane. Cylindrical − Cylindrical projections project the sphere onto a containing cylinder, and then unroll the cylinder onto the plane. To create a new projection, you can use the following function. d3.geoProjection(project) It constructs a new projection from the specified raw projection project. The project function takes the longitude and latitude of a given point in radians. You can apply the following projection in your code. var width = 400 var height = 400 var projection = d3.geo.orthographic() var projections = d3.geo.equirectangular() var project = d3.geo.gnomonic() var p = d3.geo.mercator() var pro = d3.geo.transverseMercator() .scale(100) .rotate([100,0,0]) .translate([width/2, height/2]) .clipAngle(45); Here, we can apply any one of the above projections. Let us discuss each of these projections in brief. d3.geo.orthographic() − The orthographic projection is an azimuthal projection suitable for displaying a single hemisphere; the point of perspective is at infinity. d3.geo.gnomonic() − The gnomonic projection is an azimuthal projection that projects great circles as straight lines. d3.geo.equirectangular() − The equirectangular is the simplest possible geographic projection. The identity function. It is neither equal-area nor conformal, but is sometimes used for raster data. d3.geo.mercator() − The Spherical Mercator projection is commonly used by tiled mapping libraries. d3.geo.transverseMercator() − The Transverse Mercator projection. Working Example Let us create the map of India in this example. To do this, we should adhere to the following steps. Step 1 − Apply styles − Let us add styles in map using the code below. <style> path { stroke: white; stroke-width: 0.5px; fill: grey; } .stateTN { fill: red; } .stateAP { fill: blue; } .stateMP{ fill: green; } </style> Here, we have applied particular colors for state TN, AP and MP. Step 2 − Include topojson script − TopoJSON is an extension of GeoJSON that encodes topology, which is defined below. <script src = “http://d3js.org/topojson.v0.min.js”></script> We can include this script in our coding. Step 3 − Define variables − Add variables in your script, using the code below. var width = 600; var height = 400; var projection = d3.geo.mercator() .center([78, 22]) .scale(680) .translate([width / 2, height / 2]); Here, SVG width is 600 and height is 400. The screen is a two-dimensional space and we are trying to present a three-dimensional object. So, we can grievously distort the land size / shape using the d3.geo.mercator() function. The center is specified [78, 22], this sets the projection’s center to the specified location as a two-element array of longitude and latitude in degrees and returns the projection. Here, the map has been centered on 78 degrees West and 22 degrees North. The Scale is specified as 680, this sets the projection’s scale factor to the specified value. If the scale is not specified, it returns the current scale factor, which defaults to 150. It is important to note that scale factors are not consistent across projections. Step 4 − Append SVG − Now, append the SVG attributes. var svg = d3.select(“body”).append(“svg”) .attr(“width”, width) .attr(“height”, height); Step 5 − Create path − The following portion of code creates a new geographic path generator. var path = d3.geo.path() .projection(projection); Here, the path generator (d3.geo.path()) is used to specify a projection type (.projection), which was defined earlier as a Mercator projection using the variable projection. Step 6 − Generate data − indiatopo.json – This file contains so many records, which we can easily download from the following attachment. Download indiatopo.json file After the file has been downloaded, we can add it our D3 location. The sample format is shown below. {“type”:”Topology”,”transform”:{“scale”:[0.002923182318231823,0.0027427542754275428], “translate”:[68.1862,8.0765]},”objects”: {“states”:{“type”:”GeometryCollection”, “geometries”:[{“type”:”MultiPolygon”,”id”:”AP”,”arcs”: [[[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24, 25,26,27,28,29,30,31,32,33,34]],[[35,36,37,38,39,40,41]],[[42]], [[43,44,45]],[[46]],[[47]],[[48]],[[49]],[[50]],[[51]],[[52,53]], [[54]],[[55]],[[56]],[[57,58]],[[59]],[[60]],[[61,62,63]],[[64]], [[65]],[[66]],[[67]],[[68]],[[69]],[[-41,70]], [[71]],[[72]],[[73]],[[74]],[[75]]], “properties”:{“name”:”Andhra Pradesh”}},{“type”:”MultiPolygon”, “id”:”AR”,”arcs”:[[[76,77,78,79,80,81,82]]], “properties”:{“name”:”Arunachal Pradesh”}},{“type”:”MultiPolygon”, “id”:”AS”,”arcs”:[[[83,84,85,86,87,88,89,90, 91,92,93,94,95,96,97,98,99,100,101,102,103]], [[104,105,106,107]],[[108,109]]], …… …………………………………. Step 7 − Draw map − Now, read the data from the indiatopo.json file and draw the map. d3.json(“indiatopo.json”, function(error, topology) { g.selectAll(“path”) .data(topojson.object(topology, topology.objects.states) .geometries) .enter() .append(“path”) .attr(“class”, function(d) { return “state” + d.id; }) .attr(“d”, path) }); Here, we will load the TopoJSON file with the coordinates for the India map (indiatopo.json). Then we declare that we are going to act on all the path elements in the graphic. It is defined as, g.selectAll(“path”). We will then pull the data that defines the countries from the TopoJSON file. .data(topojson.object(topology, topology.objects.states) .geometries) Finally, we will add it to the data that we are going to display using the .enter() method and then we append that data as path elements using the .append(“path”) method. Print Page Previous Next Advertisements ”;

D3.js – Selection API

D3.js – Selection API ”; Previous Next Selections are powerful data-driven transformation of the document object model (DOM). It is used to set Attributes, Styles, Properties, HTML or Text Content and much more. This chapter explains the selections API in detail. Configuring the API You can configure the API directly using the script below. <script src = “https://d3js.org/d3-selection.v1.min.js”></script> <script> </script> Selection API Methods Following are the most important methods in selection API. d3.selection() d3.select(selector) d3.selectAll(selector) selection.selectAll(selector) selection.filter(filter) selection.merge(other) d3.matcher(selector) d3.creator(name) selection.each(function) selection.call(function[, arguments…]) d3.local() local.set(node, value) local.get(node) local.remove(node) Let us now discuss each of these in detail. d3.selection() This method is used to select the root element. This function can also be used to test for selections or to extend the selection d3js. d3.select(selector) This method is used to select the first element that matches the specified selector string. Example − Let us consider the following example. var body = d3.select(“body”); If the selector is not a string, then it selects the specified node, which is defined below. d3.select(“p”).style(“color”, “red”); d3.selectAll(selector) This method selects all the elements that match the specified selector string. Example − Let us consider the following example. var body = d3.selectAll(“body”); If the selector is not a string, then it selects the specified array of nodes, which is defined below. d3.selectAll(“body”).style(“color”, “red”); selection.selectAll(selector) This method is used to select an element. It selects the descendant elements that match the specified selector string. The elements in the returned selection are grouped by their corresponding parent node in this selection. If no element matches the specified selector for the current element, or if the selector is null, the group at the current index will be empty. Example − Let us consider the following example. var b = d3.selectAll(“p”).selectAll(“b”); selection.filter(filter) This method is used to filter the selection, returning a new selection that contains only the elements for which the specified filter is true. Example − Let us consider the following example. var even = d3.selectAll(“tr”).filter(“:nth-child(odd)”); Here, filter a selection of table rows returns only odd. selection.merge(other) This method is used to return a new selection merging with the specified other selection. Example − Let us consider the following example. var rect = svg.selectAll(“rect”).data(data); rect.enter().append(“rect”).merge(rect); d3.matcher(selector) This method is used to assign the specified selector. It returns a function, which returns true. Example − Let us consider the following example. var p = selection.filter(d3.matcher(“p”)); d3.creator(name) This method is used to assign the specified element name It returns a function, which creates an element of the given name, assuming that this is the parent element. Example − Let us consider the following example. selection.append(d3.creator(“p”)); selection.each(function) This method is used to invoke the specified function for each selected element, in the order passed by the current datum (d), the current index (i) and the current group (nodes) with this as the current DOM element (nodes[i]). It is explained below. parent.each(function(p, j) { d3.select(this) .selectAll(“.child”) .text(function(d, i) { return “child ” + d.name + ” of ” + p.name; }); }); selection.call(function[, arguments…]) It is used to invoke the specified function exactly once. The syntax is shown below. function name(selection, first, last) { selection.attr(“first-name”, first).attr(“last-name”, last); } This method can be specified as shown below. d3.selectAll(“p”).call(name, “Adam”, “David”); d3.local() D3 local allows you to define the local state that is independent of data. Example − Let us consider the following example. var data = d3.local(); Unlike var, the value of each local is also scoped by the DOM. local.set(node, value) This method sets the value of this local on the specified node to the value. Example − Let us consider the following example. selection.each(function(d) { data.set(this, d.value); }); local.get(node) This method returns the value of this local on the specified node. If the node does not define this local, then it returns the value from the nearest ancestor that defines it. local.remove(node) This method deletes this local’s value from the specified node. It returns true, if the node defined, otherwise returns false. Print Page Previous Next Advertisements ”;

D3.js – Introduction

D3.js – Introduction ”; Previous Next Data visualization is the presentation of data in a pictorial or graphical format. The primary goal of data visualization is to communicate information clearly and efficiently via statistical graphics, plots and information graphics. Data visualization helps us to communicate our insights quickly and effectively. Any type of data, which is represented by a visualization allows users to compare the data, generate analytic reports, understand patterns and thus helps them to take the decision. Data visualizations can be interactive, so that users analyze specific data in the chart. Well, Data visualizations can be developed and integrated in regular websites and even mobile applications using different JavaScript frameworks. What is D3.js? D3.js is a JavaScript library used to create interactive visualizations in the browser. The D3.js library allows us to manipulate elements of a webpage in the context of a data set. These elements can be HTML, SVG, or Canvas elements and can be introduced, removed, or edited according to the contents of the data set. It is a library for manipulating the DOM objects. D3.js can be a valuable aid in data exploration, it gives you control over your data”s representation and lets you add interactivity. Why Do We Need D3.js? D3.js is one of the premier framework when compare to other libraries. This is because it works on the web and its data visualizations are par excellence. Another reason it has worked so well is owing to its flexibility. Since it works seamlessly with the existing web technologies and can manipulate any part of the document object model, it is as flexible as the Client Side Web Technology Stack (HTML, CSS, and SVG). It has a great community support and is easier to learn. D3.js Features D3.js is one of the best data visualization framework and it can be used to generate simple as well as complex visualizations along with user interaction and transition effects. Some of its salient features are listed below − Extremely flexible. Easy to use and fast. Supports large datasets. Declarative programming. Code reusability. Has wide variety of curve generating functions. Associates data to an element or group of elements in the html page. D3.js Benefits D3.js is an open source project and works without any plugin. It requires very less code and comes up with the following benefits − Great data visualization. It is modular. You can download a small piece of D3.js, which you want to use. No need to load the whole library every time. Easy to build a charting component. DOM manipulation. In the next chapter, we will understand how to install D3.js on our system. Print Page Previous Next Advertisements ”;

D3.js – Data Join

D3.js – Data Join ”; Previous Next Data join is another important concept in D3.js. It works along with selections and enables us to manipulate the HTML document with respect to our data set (a series of numerical values). By default, D3.js gives data set the highest priority in its methods and each item in the data set corresponds to a HTML element. This chapter explains data joins in detail. What is a Data Join? Data join enables us to inject, modify and remove elements (HTML element as well as embedded SVG elements) based on the data set in the existing HTML document. By default, each data item in the data set corresponds to an element (graphical) in the document. As the data set changes, the corresponding element can also be manipulated easily. Data join creates a close relationship between our data and graphical elements of the document. Data join makes manipulation of the elements based on the data set a very simple and easy process. How Data Join Works? The primary purpose of the Data join is to map the elements of the existing document with the given data set. It creates a virtual representation of the document with respect to the given data set and provides methods to work with the virtual representation. Let us consider a simple data set as shown below. [10, 20, 30, 25, 15] The data set has five items and so, it can be mapped to five elements of the document. Let us map it to the li element of the following document using the selector”s selectAll() method and data join”s data() method. HTML <ul id = “list”> <li><li> <li></li> </ul> D3.js code d3.select(“#list”).selectAll(“li”).data([10, 20, 30, 25, 15]); Now, there are five virtual elements in the document. The first two virtual elements are the two li element defined in the document as shown below. 1. li – 10 2. li – 20 We can use all the selector”s element modifying methods like attr(), style(), text(), etc., for the first two li as shown below. d3.select(“#list”).selectAll(“li”) .data([10, 20, 30, 25, 15]) .text(function(d) { return d; }); The function in the text() method is used to get the li elements mapped data. Here, d represent 10 for first li element and 20 for second li element. The next three elements can be mapped to any elements and it can be done using the data join”s enter() and selector”s append() method. The enter() method gives access to the remaining data (which is not mapped to the existing elements) and the append() method is used to create a new element from the corresponding data. Let us create li for the remaining data items as well. The data map is as follows − 3. li – 30 4. li – 25 5. li – 15 The code to create new a li element is as follows − d3.select(“#list”).selectAll(“li”) .data([10, 20, 30, 25, 15]) .text(function(d) { return “This is pre-existing element and the value is ” + d; }) .enter() .append(“li”) .text(function(d) { return “This is dynamically created element and the value is ” + d; }); Data join provides another method called as the exit() method to process the data items removed dynamically from the data set as shown below. d3.selectAll(“li”) .data([10, 20, 30, 15]) .exit() .remove() Here, we have removed the fourth item from the data set and its corresponding li using the exit() and the remove() methods. The complete code is as follows − Live Demo <!DOCTYPE html> <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> <style> body { font-family: Arial; } </style> </head> <body> <ul id = “list”> <li></li> <li></li> </ul> <input type = “button” name = “remove” value = “Remove fourth value” onclick = “javascript:remove()” /> <script> d3.select(“#list”).selectAll(“li”) .data([10, 20, 30, 25, 15]) .text(function(d) { return “This is pre-existing element and the value is ” + d; }) .enter() .append(“li”) .text(function(d) { return “This is dynamically created element and the value is ” + d; }); function remove() { d3.selectAll(“li”) .data([10, 20, 30, 15]) .exit() .remove() } </script> </body> </html> The result of the above code will be as follows −

D3.js – Home

D3.js Tutorial PDF Version Quick Guide Resources Job Search Discussion D3 stands for Data-Driven Documents. D3.js is a JavaScript library for manipulating documents based on data. D3.js is a dynamic, interactive, online data visualizations framework used in a large number of websites. D3.js is written by Mike Bostock, created as a successor to an earlier visualization toolkit called Protovis. This tutorial will give you a complete knowledge on D3.jsframework. This is an introductory tutorial, which covers the basics of Data-Driven Documents and explains how to deal with its various components and sub-components. Audience This tutorial is prepared for professionals who are aspiring to make a career in online data visualization. This tutorial is intended to make you comfortable in getting started with the Data-Driven Documents and its various functions. Prerequisites Before proceeding with the various types of concepts given in this tutorial, it is being assumed that the readers are already aware about what a Framework is. In addition to this, it will be very helpful, if the readers have a sound knowledge on HTML, CSS and JavaScript. Print Page Previous Next Advertisements ”;

D3.js – Concepts

D3.js – Concepts ”; Previous Next D3.js is an open source JavaScript library for − Data-driven manipulation of the Document Object Model (DOM). Working with data and shapes. Laying out visual elements for linear, hierarchical, network and geographic data. Enabling smooth transitions between user interface (UI) states. Enabling effective user interaction. Web Standards Before we can start using D3.js to create visualizations, we need to get familiar with web standards. The following web standards are heavily used in D3.js. HyperText Markup Language (HTML) Document Object Model (DOM) Cascading Style Sheets (CSS) Scalable Vector Graphics (SVG) JavaScript Let us go through each of these web standards one by one in detail. HyperText Markup Language (HTML) As we know, HTML is used to structure the content of the webpage. It is stored in a text file with the extension “.html”. Example − A typical bare-bones HTML example looks like this <!DOCTYPE html> <html lang = “en”> <head> <meta charset = “UTF-8”> <title></title> </head> <body> </body> </html> Document Object Model (DOM) When a HTML page is loaded by a browser, it is converted to a hierarchical structure. Every tag in HTML is converted to an element / object in the DOM with a parent-child hierarchy. It makes our HTML more logically structured. Once the DOM is formed, it becomes easier to manipulate (add/modify/remove) the elements on the page. Let us understand the DOM using the following HTML document − <!DOCTYPE html> <html lang = “en”> <head> <title>My Document</title> </head> <body> <div> <h1>Greeting</h1> <p>Hello World!</p> </div> </body> </html> The document object model of the above HTML document is as follows, Cascading Style Sheets (CSS) While HTML gives a structure to the webpage, CSS styles makes the webpage more pleasant to look at. CSS is a Style Sheet Language used to describe the presentation of a document written in HTML or XML (including XML dialects like SVG or XHTML). CSS describes how elements should be rendered on a webpage. Scalable Vector Graphics (SVG) SVG is a way to render images on the webpage. SVG is not a direct image, but is just a way to create images using text. As its name suggests, it is a Scalable Vector. It scales itself according to the size of the browser, so resizing your browser will not distort the image. All browsers support SVG except IE 8 and below. Data visualizations are visual representations and it is convenient to use SVG to render visualizations using the D3.js. Think of SVG as a canvas on which we can paint different shapes. So to start with, let us create an SVG tag − <svg width = “500” height = “500”></<svg> The default measurement for SVG is pixels, so we do not need to specify if our unit is pixel. Now, if we want to draw a rectangle, we can draw it using the code below − <svg width = “500” height = “500”> <rect x = “0” y = “0” width = “300” height = “200”></rect> </svg> We can draw other shapes in SVG such as − Line, Circle, Ellipse, Text and Path. Just like styling HTML elements, styling SVG elements is simple. Let us set the background color of the rectangle to yellow. For that, we need to add an attribute “fill” and specify the value as yellow as shown below − <svg width = “500” height = “500”> <rect x = “0” y = “0” width = “300” height = “200” fill = “yellow”></rect> </svg> JavaScript JavaScript is a loosely typed client side scripting language that executes in the user”s browser. JavaScript interacts with HTML elements (DOM elements) in order to make the web user interface interactive. JavaScript implements the ECMAScript Standards, which includes core features based on ECMA-262 specifications as well as other features, which are not based on the ECMAScript standards. JavaScript knowledge is a prerequisite for D3.js. Print Page Previous Next Advertisements ”;