D3.js – Working Example ”; Previous Next Let us perform an animated bar chart in this chapter. For this example, we take the data.csv file used in the previous chapter of the population records as dataset and generate an animated bar chart. To do this, we need to perform the following steps − Step 1 − Apply styles − Apply CSS styles using the coding given below. <style> .bar { fill: green; } .highlight { fill: red; } .title { fill: blue; font-weight: bold; } </style> Step 2 − Define variables − Let us define the SVG attributes using the script below. <script> var svg = d3.select(“svg”), margin = 200, width = svg.attr(“width”) – margin, height = svg.attr(“height”) – margin; </script> Step 3 − Append text − Now, append text and apply the transformation using the coding below. svg.append(“text”) .attr(“transform”, “translate(100,0)”) .attr(“x”, 50) .attr(“y”, 50) .attr(“font-size”, “20px”) .attr(“class”, “title”) .text(“Population bar chart”) Step 4 − Create scale range − In this step, we can create a scale range and append the group elements. It is defined below. var x = d3.scaleBand().range([0, width]).padding(0.4), y = d3.scaleLinear() .range([height, 0]); var g = svg.append(“g”) .attr(“transform”, “translate(” + 100 + “,” + 100 + “)”); Step 5 − Read data − We have already created the data.csv file in our previous examples. The same file, we have used here. year,population 2006,40 2008,45 2010,48 2012,51 2014,53 2016,57 2017,62 Now, read the above file using the code below. d3.csv(“data.csv”, function(error, data) { if (error) { throw error; } Step 6 − Set domain − Now, set the domain using the coding below. x.domain(data.map(function(d) { return d.year; })); y.domain([0, d3.max(data, function(d) { return d.population; })]); Step 7 − Add X-axis − Now, you can add the X-axis to the transformation. It is shown below. g.append(“g”) .attr(“transform”, “translate(0,” + height + “)”) .call(d3.axisBottom(x)).append(“text”) .attr(“y”, height – 250).attr(“x”, width – 100) .attr(“text-anchor”, “end”).attr(“font-size”, “18px”) .attr(“stroke”, “blue”).text(“year”); Step 8 − Add Y-axis − Add the Y-axis to the transformation using the code given below. g.append(“g”) .append(“text”).attr(“transform”, “rotate(-90)”) .attr(“y”, 6).attr(“dy”, “-5.1em”) .attr(“text-anchor”, “end”).attr(“font-size”, “18px”) .attr(“stroke”, “blue”).text(“population”); Step 9 − Append group elements − Now, append the group elements and apply transformation to Y-axis as defined below. g.append(“g”) .attr(“transform”, “translate(0, 0)”) .call(d3.axisLeft(y)) Step 10 − Select the bar class − Now, select all the elements in the bar class as defined below. g.selectAll(“.bar”) .data(data).enter() .append(“rect”) .attr(“class”, “bar”) .on(“mouseover”, onMouseOver) .on(“mouseout”, onMouseOut) .attr(“x”, function(d) { return x(d.year); }) .attr(“y”, function(d) { return y(d.population); }) .attr(“width”, x.bandwidth()) .transition() .ease(d3.easeLinear) .duration(200) .delay(function (d, i) { return i * 25; }) .attr(“height”, function(d) { return height – y(d.population); }); }); Here, we added the listener event for the mouseout and mouseover to perform animation. It applies the animation, when the mouse hovers over a particular bar and goes out of it. These functions are explained in the following step. The .ease(d3.easeLinear) function is used to perform apparent motion in animation. It processes the slow-in and the slow-out motion with a duration of 200. The delay can be calculated using − .delay(function (d, i) { return i * 25; }) Step 11 − Mouseover event handler function − Let us create a mouseover event handler to handle a mouse event as shown below. function onMouseOver(d, i) { d3.select(this) .attr(”class”, ”highlight”); d3.select(this) .transition() .duration(200) .attr(”width”, x.bandwidth() + 5) .attr(“y”, function(d) { return y(d.population) – 10; }) .attr(“height”, function(d) { return height – y(d.population) + 10; }); g.append(“text”) .attr(”class”, ”val”) .attr(”x”, function() { return x(d.year); }) .attr(”y”, function() { return y(d.value) – 10; }) } Here, in the mouseover event, we want to increase the bar width and height, and the bar color of the selected bar to red. For the color, we have added a class ‘highlight’, which changes the color of the selected bar to red. A transition function to the bar for the duration of 200 milliseconds. When we increase the width of the bar by 5px, and the height by 10px, the transition from the previous width and height of the bar to the new width and height will be for the duration of 200 milliseconds. Next, we calculated a new ‘y’ value to the bar, so that the bar does not distort due to the new height value. Step 12 − Mouseout event handler function − Let us create a mouseout event handler to handle a mouse event. It is defined below. function onMouseOut(d, i) { d3.select(this).attr(”class”, ”bar”); d3.select(this) .transition() .duration(400).attr(”width”, x.bandwidth()) .attr(“y”, function(d) { return y(d.population); }) .attr(“height”, function(d) { return height – y(d.population); }); d3.selectAll(”.val”) .remove() } Here, in the mouseout event, we want to remove the selection features that we had applied in the mouseover event. Therefore, we revert the bar class to the original ‘bar’ class and restore the original width and height of the selected bar and restore the y value to the original value. The d3.selectAll(‘.val’).remove() function is used to remove the text value we had added during the bar selection. Step 13 − Working Example − The complete program is given in the following code block. Create a webpage animated_bar.html and add the following changes to it. <!DOCTYPE html> <html> <head> <style> .bar { fill: green; } .highlight { fill: red; } .title { fill: blue; font-weight: bold; } </style> <script src = “https://d3js.org/d3.v4.min.js”></script> <title> Animated bar chart </title> </head> <body> <svg width = “500” height = “500”></svg> <script> var svg = d3.select(“svg”), margin = 200, width = svg.attr(“width”) – margin, height = svg.attr(“height”) – margin; svg.append(“text”) .attr(“transform”, “translate(100,0)”) .attr(“x”, 50).attr(“y”, 50) .attr(“font-size”, “20px”) .attr(“class”, “title”) .text(“Population bar chart”) var x = d3.scaleBand().range([0, width]).padding(0.4), y = d3.scaleLinear().range([height, 0]); var g = svg.append(“g”) .attr(“transform”, “translate(” + 100 + “,” + 100 + “)”); d3.csv(“data.csv”, function(error, data) { if (error) { throw error; } x.domain(data.map(function(d) { return d.year; })); y.domain([0, d3.max(data, function(d) { return d.population; })]); g.append(“g”) .attr(“transform”, “translate(0,” + height + “)”) .call(d3.axisBottom(x)) .append(“text”) .attr(“y”, height – 250) .attr(“x”, width – 100) .attr(“text-anchor”, “end”) .attr(“font-size”, “18px”) .attr(“stroke”, “blue”).text(“year”); g.append(“g”) .append(“text”) .attr(“transform”, “rotate(-90)”) .attr(“y”, 6)
Category: d3js
D3.js – SVG Transformation
D3.js – SVG Transformation ”; Previous Next SVG provides options to transform a single SVG shape element or group of SVG elements. SVG transform supports Translate, Scale, Rotate and Skew. Let us learn transformation in this chapter. Introduction to SVG Transformation SVG introduces a new attribute, transform to support transformation. The possible values are one or more of the following, Translate − It takes two options, tx refers translation along the x-axis and ty refers to the translation along the y-axis. For Example− translate(30 30). Rotate − It takes three options, angle refers rotation angle, cx and cy refers to the center of the rotation in the x and y axis. If cx and cy are not specified, then it defaults to the current origin of the coordinate system. For Example − rotate(60). Scale − It takes two options, sx refers to the scaling factor along the x-axis and sy refers to the scaling factor along the y-axis. Here, sy is optional and it takes the value of sx, if it is not specified. For Example − scale(10). Skew (SkewX and SkewY) − It takes a single option; the skew-angle refers to the angle along the x-axis for SkewX and the angle along the y-axis for SkewY. For Example − skewx(20). An example of the SVG rectangle with translate, which is described as follows − Live Demo <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> </head> <body> <svg width = “300” height = “300”> <rect x = “20” y = “20” width = “60” height = “60” fill = “green” transform = “translate(30 30)”> </rect> </svg> </body> </html> The above code will yield the following result. More than one transformation can be specified for a single SVG element using space as separation. If more than one value is specified, the transformation will be applied one by one sequentially in the order specified. Live Demo <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> </head> <body> <svg width = “300” height = “300”> <rect x = “20” y = “20” width = “60” height = “60” fill = “green” transform = “translate(60 60) rotate(45)”> </rect> </svg> </body> </html> The above code will yield the following result. Transformation can be applied to the SVG group element as well. This enables to transform complex graphics defined in the SVG as described below. Live Demo <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> </head> <body> <svg width = “300” height = “300”> <g transform = “translate(60,60) rotate(30)”> <rect x = “20” y = “20” width = “60” height = “30” fill = “green”> </rect> <circle cx = “0” cy = “0” r = “30” fill = “red”/> </g> </svg> </body> </html> The above code will yield the following result. A Minimal Example To create an SVG image, try to scale, and rotate it using transformation, let us follow the steps given below. Step 1 − Create an SVG image and set width as 300 pixels and height as 300 pixels. <svg width = “300” height = “300”> </svg> Step 2 − Create an SVG group. <svg width = “300” height = “300”> <g> </g> </svg> Step 3 − Create a rectangle of length 60 and height 30 and fill it with green color. <svg width = “300” height = “300”> <g> <rect x = “20” y = “20” width = “60” height = “30” fill = “green”> </rect> </g> </svg> Step 4 − Create a circle of radius 30 and fill it with red color. <svg width = “300” height = “300”> <g> <rect x = “20” y = “20” width = “60” height = “30” fill = “green”> </rect> <circle cx = “0” cy = “0” r = “30” fill = “red”/> </g> </svg> Step 5 − Add a transform attribute and add translate and rotate as shown below. <svg width = “300” height = “300”> <g transform = “translate(60,60) rotate(30)”> <rect x = “20” y = “20” width = “60” height = “60” fill = “green”> </rect> <circle cx = “0” cy = “0” r = “30” fill = “red”/> </g> </svg> Step 6 − Create an HTML document, “svg_transform_rotate_group.html” and integrate the above SVG as explained below. 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> <div id = “svgcontainer”> <svg width = “300” height = “300”> <g transform = “translate(60,60) rotate(30)”> <rect x = “20” y = “20” width = “60” height = “60” fill = “green”> </rect> <circle cx = “0” cy = “0” r = “30” fill = “red”/> </g> </svg> </div> </body> </html> The above code will yield the following result. Transformation Using D3.js To create SVG using D3.js, let us follow the steps given below. Step 1 − Create a container to hold the SVG image as explained below. <div id = “svgcontainer”></div> Step 2 − Create a SVG image as explained below. var width = 300; var height = 300; var svg = d3.select(“#svgcontainer”) .append(“svg”) .attr(“width”, width) .attr(“height”, height); Step 3 − Create a SVG group element and set translate and rotate attributes. var group = svg.append(“g”).attr(“transform”, “translate(60, 60) rotate(30)”); Step 4 − Create an SVG rectangle and append it inside the group. var rect = group .append(“rect”) .attr(“x”, 20) .attr(“y”, 20) .attr(“width”, 60) .attr(“height”, 30) .attr(“fill”, “green”) Step 5 − Create an SVG circle and append it inside the group. var circle = group .append(“circle”) .attr(“cx”, 0) .attr(“cy”, 0) .attr(“r”, 30) .attr(“fill”, “red”) The complete code is as follows − Live Demo <!DOCTYPE html> <html lang = “en”> <head> <title>SVG rectangle</title> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> <style> body { font-family: Arial; } </style> </head> <body> <div id = “svgcontainer”></div> <script language = “javascript”> var width = 300; var height = 300; var svg = d3.select(“#svgcontainer”) .append(“svg”) .attr(“width”, width) .attr(“height”, height); var group = svg.append(“g”) .attr(“transform”, “translate(60, 60) rotate(30)”); var rect = group.append(“rect”) .attr(“x”, 20) .attr(“y”, 20) .attr(“width”, 60) .attr(“height”, 30) .attr(“fill”, “green”) var
D3.js – Quick Guide
D3.js – Quick Guide ”; Previous Next D3.js – Introduction 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. D3.js – Installation In this chapter, we will learn how to set up the D3.js development environment. Before we start, we need the following components − D3.js library Editor Web browser Web server Let us go through the steps one by one in detail. D3.js Library We need to include the D3.js library into your HTML webpage in order to use D3.js to create data visualization. We can do it in the following two ways − Include the D3.js library from your project”s folder. Include D3.js library from CDN (Content Delivery Network). Download D3.js Library D3.js is an open-source library and the source code of the library is freely available on the web at https://d3js.org/ website. Visit the D3.js website and download the latest version of D3.js (d3.zip). As of now, the latest version is 4.6.0. After the download is complete, unzip the file and look for d3.min.js. This is the minified version of the D3.js source code. Copy the d3.min.js file and paste it into your project”s root folder or any other folder, where you want to keep all the library files. Include the d3.min.js file in your HTML page as shown below. Example − Let us consider the following example. <!DOCTYPE html> <html lang = “en”> <head> <script src = “/path/to/d3.min.js”></script> </head> <body> <script> // write your d3 code here.. </script> </body> </html> D3.js is a JavaScript code, so we should write all our D3 code within “script” tag. We may need to manipulate the existing DOM elements, so it is advisable to write the D3 code just before the end of the “body” tag. Include D3 Library from CDN We can use the D3.js library by linking it directly into our HTML page from the Content Delivery Network (CDN). CDN is a network of servers where files are hosted and are delivered to a user based on their geographic location. If we use the CDN, we do not need to download the source code. Include the D3.js library using the CDN URL https://d3js.org/d3.v4.min.js into our page as shown below. Example − Let us consider the following example. <!DOCTYPE html> <html lang = “en”> <head> <script src = “https://d3js.org/d3.v4.min.js”></script> </head> <body> <script> // write your d3 code here.. </script> </body> </html> D3.js Editor We will need an editor to start writing your code. There are some great IDEs (Integrated Development Environment) with support for JavaScript like − Visual Studio Code WebStorm Eclipse Sublime Text These IDEs provide intelligent code completion as well as support some of the modern JavaScript frameworks. If you do not have fancy IDE, you can always use a basic editor like Notepad, VI, etc. Web Browser D3.js works on all the browsers except IE8 and lower. Web Server Most browsers serve local HTML files directly from the local file system. However, there are certain restrictions when it comes to loading external data files. In the latter chapters of this tutorial, we will be loading data from external files like CSV and JSON. Therefore, it will be easier for us, if we set up the web server right from the beginning. You can use any web server, which you are comfortable with − e.g. IIS, Apache, etc. Viewing Your Page In most cases, we can just open your HTML file in a web browser to view it.
D3.js – Delimiter-Separated Values API ”; Previous Next A delimiter is a sequence of one or more characters used to specify the boundary between separate, independent regions in plain text or other data. A field delimiter is a sequence of comma-separated values. Well, delimiter-separated values are comma separated values (CSV) or tab-separated values (TSV). This chapter explains the delimiter separated values in detail. Configuring API We can easily load the API using the following syntax. <script src = “https://d3js.org/d3-dsv.v1.min.js”></script> <script> var data = d3.csvParse(string); </script> API methods Following are the various API methods of the delimiter-separated values. d3.csvParse(string[, row]) d3.csvParseRows(string[, row]) d3.csvFormat(rows[, columns]) d3.csvFormatRows(rows) d3.tsvParse(string[, row]) d3.tsvParseRows(string[, row]) d3.tsvFormat(rows[, columns]) d3.tsvFormatRows(rows) Let us go through each of these API methods in detail. d3.csvParse(string[, row]) This method is used to parse the csv format. Consider the file data.csv that is shown below. year,population 2006,40 2008,45 2010,48 2012,51 2014,53 2016,57 2017,62 Now, we can apply the above-given function. Example − Let us consider the following example. var data = d3.csvParse(string, function(d) { return { year: new Date(+d.Year, 0, 1), // lowercase and convert “Year” to Date population: d.population }; }); Here, it Parses the specified string in the delimiter-separated values. It returns an array of objects representing the parsed rows. d3.csvParseRows(string[, row]) This method is used to parse the csv format equivalent to rows. var data = d3.csvParseRows(string, function(d, i) { return { year: new Date(+d[0], 0, 1), // convert first colum column to Date population: d[1], }; }); It parses each row in the csv file. d3.csvFormat(rows[, columns]) This method is used to format the csv rows and columns. Example − Let us consider the following example. var string = d3.csvFormat(data, [“year”, “population”]); Here, if the columns are not specified, the list of the column names that forms the header row is determined by the union of all properties on all the objects in the rows. If columns are specified, it is an array of strings representing the column names. d3.csvFormatRows(rows) This method is used to format the csv rows. Example − Let us consider the following example. var string = d3.csvFormatRows(data.map(function(d, i) { return [ d.year.getFullYear(), // Assuming d.year is a Date object. d.population ]; })); Here, it formats the specified array of string rows as delimiter-separated values, returning a string. d3.tsvParse(string[, row]) This method is used to parse the tsv format. It is similar to csvParse. d3.tsvParseRows(string[, row]) This method is used to parse the tsv format equivalent to rows. It is similar to csvParseRows function. d3.tsvFormat(rows[, columns]) This method is used to format the tsv rows and columns. d3.tsvFormatRows(rows) This method is used to format the tsv rows. Print Page Previous Next Advertisements ”;
D3.js – Requests API
D3.js – Requests API ”; Previous Next D3.js provides a request API to perform the XMLHttpRequest. This chapter explains the various requests API in detail. XMLHttpRequest XMLHttpRequest is the built-in http client to emulate the browser XMLHttpRequest object. It can be used with JS designed for browsers to improve reuse of code and allow the use of existing libraries. You can include the module in your project and use as the browser-based XHR object as explained below. var XMLHttpRequest = require(“xmlhttprequest”).XMLHttpRequest; var xhr = new XMLHttpRequest(); It supports both async and synchronous requests and it performs GET, POST, PUT, and DELETE requests. Configuring Requests You can load directly from “d3js.org” using the script below. <script src = “https://d3js.org/d3-request.v1.min.js”></script> <script> d3.json(“/path/to/sample.json”, callback); </script> Here, the requests API have built-in support for parsing JSON, CSV and TSV. You can parse additional formats by using the request or text directly. Load Text Files To load a text file, use the following syntax. d3.text(“/path/to/sample.txt”, function(error, text) { if (error) throw error; console.log(text); }); Parsing CSV files To load and parse a CSV file, use the following syntax. d3.csv(“/path/to/sample.csv”, function(error, data) { if (error) throw error; console.log(data); }); Similarly, you can load the JSON and TSV files as well. Working Example Let us go through a simple example for how to load and parse a CSV file. Before that, you need to create a CSV file named “sample.csv” in your d3 application folder as shown below. Num1,Num2 1,2 3,4 5,6 7,8 9,10 Now, create a webpage “requests.html” using the following script. <!DOCTYPE html> <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> </head> <body> <h3> D3.js Requests API </h3> <script> d3.csv(“sample.csv”, function(data) { console.log(data); }); </script> </body> </html> Now, request the browser and you will see the following response, Requests API Methods Following are some of the most commonly used Requests API methods. d3.request(url[, callback]) request.header(name[, value]) request.mimeType([type]) request.user([value]) request.password([value]) request.timeout([timeout]) request.get([data]) request.post([data]) request.send(method[, data]) request.abort() d3.csv(url[[, row], callback]) Let us now discuss each of these in brief. d3.request(url[, callback]) It returns a new request for the given URL. If a callback is assigned, it is considered as a calling request otherwise request is not yet called. It is defined below. d3.request(url) .get(callback); You can post some query parameters using the following syntax. d3.request(“/path/to/resource”) .header(“X-Requested-With”, “XMLHttpRequest”) .header(“Content-Type”, “application/x-www-form-urlencoded”) .post(“a = 2&b = 3”, callback); If you wish to specify a request header or a mime type, you must not specify a callback to the constructor. request.header(name[, value]) It is used to set the value to the request header with the specified name. If no value is specified, it removes the request header with the specified name. It is defined below. d3.request(url) .header(“Accept-Language”, “en-US”) .header(“X-Requested-With”, “XMLHttpRequest”) .get(callback); Here, X-Requested-With header to XMLHttpRequest is a default request. request.mimeType([type]) It is used to assign the mime type to the given value. It is defined below. d3.request(url) .mimeType(“text/csv”) .get(callback); request.user([value]) It is used to assign the username for authentication. If a username is not specified, it defaults to null. request.password([value]) If a value is specified, it sets the password for authentication. request.timeout([timeout]) If a timeout is specified, it sets the timeout to the specified number of milliseconds. request.get([data]) This method is used to send the request with the GET method. It is defined below. request.send(“GET”, data, callback); request.post([data]) This method is used to send the request with the POST method. It is defined below. request.send(“POST”, data, callback); request.send(method[, data]) This method is used to send the request using the given GET or POST method. request.abort() This method is used to abort the request. d3.csv(url[[, row], callback]) Returns a new request for the CSV file at the specified URL with the default Mime type text/csv. The following syntax shows with no callback. d3.request(url) .mimeType(“text/csv”) .response(function(xhr) { return d3.csvParse(xhr.responseText, row); }); If you specify a callback with the POST method, it is defined below. d3.request(url) .mimeType(“text/csv”) .response(function(xhr) { return d3.csvParse(xhr.responseText, row); }) .post(callback); Example Create a csv file named “lang.csv” in your d3 application root folder directory and add the following changes to it. Year,Language,Author 1972,C,Dennis Ritchie 1995,Java,James gosling 2011,D3 js,Mike Bostock Create a webpage “csv.html” and add the following script to it. <!DOCTYPE html> <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> </head> <body> <h3> D3.js request API</h3> <script> d3.csv(“lang.csv”, function(d) { return { year: new Date(+d.Year, 0, 1), // convert “Year” column to Date language: d.Language, author: d.Author, }; }, function(error, rows) { console.log(error); console.log(rows[0].year); }); </script> </body> </html> Now, request the browser and we will see the following response. Print Page Previous Next Advertisements ”;
D3.js – Dragging API
D3.js – Dragging API ”; Previous Next Drag and drop is one of the most familiar concept in d3.js. This chapter explains dragging and its methods in detail. Installation We can directly include dragging API using the following script. <script src = “https://d3js.org/d3-dispatch.v1.min.js”></script> <script src = “https://d3js.org/d3-selection.v1.min.js”></script> <script src = “https://d3js.org/d3-drag.v1.min.js”></script> Dragging API Methods Following are some of the most important dragging API methods in D3.js. d3.drag() drag(selection) drag.container([container]) drag.filter([filter]) drag.subject([subject]) drag.clickDistance([distance]) drag.on(typenames, [listener]) d3.dragDisable(window) d3.dragEnable(window[, noclick]) Let us now understand each of these in detail. d3.drag() This method is used to create a new dragging. You can call this method using the following script. <script> var drag = d3.drag(); </script> drag(selection) This method is used to apply the dragging to the specified selection. You can invoke this function using selection.call. A simple example is defined below. d3.select(“.node”).call(d3.drag().on(“drag”, mousemove)); Here, the drag behavior applied to the selected elements is via selection.call. drag.container([container]) It is used to set the container to the specified function for dragging. If a container is not specified, it returns the current accessor. To drag any graphical elements with a Canvas, you can redefine the container as itself. It is defined below. function container() { return this; } drag.filter([filter]) It is used to set the filter for the specified function. If the filter is not specified, it returns the current filter as defined below. function filter() { return !d3.event.button; } drag.subject([subject]) It is used to set the subject to the specified function for dragging and is defined below. function subject(d) { return d = = null ? {x: d3.event.x, y: d3.event.y} : d; } Here, the subject represents the thing being dragged. For example, if you want to drag rectangle elements in SVG, the default subject is datum of the rectangle being dragged. drag.clickDistance([distance]) This method is used to set the maximum distance for clicking a mousedown and mouseup event. If distance is not specified, it points to zero. drag.on(typenames, [listener]) This method is used to set the event listener for the specified typenames for dragging. The typenames is a string containing one or more typename separated by whitespace. Each typename is a type, optionally followed by a period (.) and a name, such as drag.one and drag.two. This type should be from one of the following − start − starts a new pointer. drag − drags an active pointer. end − Inactive an active pointer. d3.dragDisable(window) This method is used to disable the drag and drop selection. It prevents mousedown event action. Most of the selected browsers supports this action by default. If not supported, you can set the CSS property to none. d3.dragEnable(window[, noclick]) This method is used to enable the drag and drop selection on the specified window location. It is used to call mouseup event action. If you assign the noclick value is true then click event expires a zero millisecond timeout. Dragging API – Drag Events The D3.event method is used to set the drag event. It consists of the following fields − Target − It represents the drag behavior. Type − It is a string and can be any one of the following– “start”, “drag” or “end”. Subject − The drag subject, defined by drag.subject. event.on(typenames, [listener]) The event object exposes the event.on method to perform dragging. It is defined as follows. d3.event.on(“drag”, dragged).on(“end”, ended); Print Page Previous Next Advertisements ”;
D3.js – Graphs
D3.js – Graphs ”; Previous Next A Graph is a 2-dimensional flat space represented as a rectangle. Graphs have a coordinate space where x = 0 and y = 0 coordinates fall on the bottom left. According to mathematical Cartesian coordinate space, graphs have the X coordinate growing from left to right and the Y coordinate growing from bottom to top. When we talk about drawing a circle with x = 30 and y = 30 coordinates, we go 30 units from the bottom left to the right and then we go 30 units up. SVG Coordinate Space SVG Coordinate Space works in the same way that a mathematical graph coordinate space works, except for two important features − SVG Coordinate space has x = 0 and y = 0 coordinates fall on the top left. SVG Coordinate space has the Y coordinate growing from top to bottom. SVG Coordinate Space Graph When we talk about drawing a circle with x = 30 and y = 30 coordinates in the SVG Coordinate Space, we go 30 units from the top left to the right and then we go down 30 units up. It is defined as follows. var svgContainer = d3 .select(“body”) .append(“svg”) .attr(“width”, 200) .attr(“height”, 200); Consider, SVG element as a graph 200 units wide and 200 units tall. We now know that the X and Y zero coordinates are at the top left. We also now know that as the Y coordinate grows, it will move from the top to the bottom of our graph. You can style the SVG elements as shown below. var svgContainer = d3 .select(“body”).append(“svg”) .attr(“width”, 200) .attr(“height”, 200) .style(“border”, “1px solid black”); Graph Example Let us consider an example of the Line graph. Line Graph − A line graph is used to visualize the value of something over time. It compares two variables. Each variable is plotted along an axis. A line graph has a vertical axis and a horizontal axis. In this example graph, we can take csv file records as Indian States Population Growth form year 2006 to 2017. Let us first create a data.csv to show the population records. Create a new csv file in your D3 folder − year,population 2006,40 2008,45 2010,48 2012,51 2014,53 2016,57 2017,62 Now, save the file and perform the following steps to draw a line graph in D3. Let us go through each step in detail. Step 1 − Adding styles − Let us add a style to the line class using the code given below. .line { fill: none; stroke: green; stroke-width: 5px; } Step 2 − Define variables − The SVG attributes are defined below. var margin = {top: 20, right: 20, bottom: 30, left: 50}, width = 960 – margin.left – margin.right, height = 500 – margin.top – margin.bottom; Here, the first line defines the four margins, which surround the block where the graph is positioned. Step 3 − Define line − Draw a new line using the d3.line() function, which is shown below. var valueline = d3.line() .x(function(d) { return x(d.year); }) .y(function(d) { return y(d.population); }); Here, Year represents the data in the X-axis records and the population refers to the data in the Y-axis. Step 4 − Append SVG attributes − Append SVG attributes and group elements using the code below. var svg = d3.select(“body”).append(“svg”) .attr(“width”, width + margin.left + margin.right) .attr(“height”, height + margin.top + margin.bottom) .append(“g”).attr(“transform”, “translate(” + margin.left + “,” + margin.top + “)”); Here, we have appended the group elements and applied the transformation. Step 5 − Read data − Now, we can read data from our dataset data.csv. d3.csv(“data.csv”, function(error, data) { if (error) throw error; } Here, the data.csv is not present, it throws an error. Step 6 − Format data − Now, format the data using the code below. data.forEach(function(d) { d.year = d.year; d.population = +d.population; }); This above code ensures that all the values that are pulled out of the csv file are set and formatted correctly. Each row consists of two values − one value for ‘year’ and another value for ‘population’. The function is pulling out values of ‘year’ and ‘population’ one row at a time. Step 7 − Set scale range − After data formatted, you can set the scale range for X and Y. x.domain(d3.extent(data, function(d) { return d.year; })); y.domain([0, d3.max(data, function(d) { return d.population; })]); Step 8 − Append path − Append path and data as shown below. svg.append(“path”).data([data]) .attr(“class”, “line”).attr(“d”, valueline); Step 9 − Add X-axis − Now, you can add X-axis using the code below. svg.append(“g”) .attr(“transform”, “translate(0,” + height + “)”) .call(d3.axisBottom(x)); Step 10 − Add Y-axis − We can add Y-axis to the group as shown below. svg.append(“g”) .call(d3.axisLeft(y)); Step 11 − Working Example − The complete code is given in the following code block. Create a simple webpage linegraphs.html and add the following changes to it. graph.html <!DOCTYPE html> <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> <style> .line { fill: none; stroke: green; stroke-width: 5px; } </style> </head> <body> <script> // set the dimensions and margins of the graph var margin = {top: 20, right: 20, bottom: 30, left: 50}, width = 960 – margin.left – margin.right, height = 500 – margin.top – margin.bottom; // set the ranges var x = d3.scaleTime().range([0, width]); var y = d3.scaleLinear().range([height, 0]); // define the line var valueline = d3.line() .x(function(d) { return x(d.year); }) .y(function(d) { return y(d.population); }); // append the svg obgect to the body of the page // appends a ”group” element to ”svg” // moves the ”group” element to the top left margin var svg = d3.select(“body”).append(“svg”) .attr(“width”, width + margin.left + margin.right) .attr(“height”, height + margin.top + margin.bottom) .append(“g”).attr(“transform”, “translate(” + margin.left + “,” + margin.top + “)”); // Get the data d3.csv(“data.csv”, function(error, data) { if (error) throw error; // format the data data.forEach(function(d) { d.year = d.year; d.population = +d.population; }); // Scale the range of the data x.domain(d3.extent(data,
D3.js – Installation
D3.js – Installation ”; Previous Next In this chapter, we will learn how to set up the D3.js development environment. Before we start, we need the following components − D3.js library Editor Web browser Web server Let us go through the steps one by one in detail. D3.js Library We need to include the D3.js library into your HTML webpage in order to use D3.js to create data visualization. We can do it in the following two ways − Include the D3.js library from your project”s folder. Include D3.js library from CDN (Content Delivery Network). Download D3.js Library D3.js is an open-source library and the source code of the library is freely available on the web at https://d3js.org/ website. Visit the D3.js website and download the latest version of D3.js (d3.zip). As of now, the latest version is 4.6.0. After the download is complete, unzip the file and look for d3.min.js. This is the minified version of the D3.js source code. Copy the d3.min.js file and paste it into your project”s root folder or any other folder, where you want to keep all the library files. Include the d3.min.js file in your HTML page as shown below. Example − Let us consider the following example. <!DOCTYPE html> <html lang = “en”> <head> <script src = “/path/to/d3.min.js”></script> </head> <body> <script> // write your d3 code here.. </script> </body> </html> D3.js is a JavaScript code, so we should write all our D3 code within “script” tag. We may need to manipulate the existing DOM elements, so it is advisable to write the D3 code just before the end of the “body” tag. Include D3 Library from CDN We can use the D3.js library by linking it directly into our HTML page from the Content Delivery Network (CDN). CDN is a network of servers where files are hosted and are delivered to a user based on their geographic location. If we use the CDN, we do not need to download the source code. Include the D3.js library using the CDN URL https://d3js.org/d3.v4.min.js into our page as shown below. Example − Let us consider the following example. <!DOCTYPE html> <html lang = “en”> <head> <script src = “https://d3js.org/d3.v4.min.js”></script> </head> <body> <script> // write your d3 code here.. </script> </body> </html> D3.js Editor We will need an editor to start writing your code. There are some great IDEs (Integrated Development Environment) with support for JavaScript like − Visual Studio Code WebStorm Eclipse Sublime Text These IDEs provide intelligent code completion as well as support some of the modern JavaScript frameworks. If you do not have fancy IDE, you can always use a basic editor like Notepad, VI, etc. Web Browser D3.js works on all the browsers except IE8 and lower. Web Server Most browsers serve local HTML files directly from the local file system. However, there are certain restrictions when it comes to loading external data files. In the latter chapters of this tutorial, we will be loading data from external files like CSV and JSON. Therefore, it will be easier for us, if we set up the web server right from the beginning. You can use any web server, which you are comfortable with − e.g. IIS, Apache, etc. Viewing Your Page In most cases, we can just open your HTML file in a web browser to view it. However, when loading external data sources, it is more reliable to run a local web server and view your page from the server (http://localhost:8080). Print Page Previous Next Advertisements ”;
D3.js – Drawing Charts
D3.js – Drawing Charts ”; Previous Next D3.js is used to create a static SVG chart. It helps to draw the following charts − Bar Chart Circle Chart Pie Chart Donut Chart Line Chart Bubble Chart, etc. This chapter explains about drawing charts in D3. Let us understand each of these in detail. Bar Chart Bar charts are one of the most commonly used types of graph and are used to display and compare the number, frequency or other measure (e.g. mean) for different discrete categories or groups. This graph is constructed in such a way that the heights or lengths of the different bars are proportional to the size of the category they represent. The x-axis (the horizontal axis) represents the different categories it has no scale. The y axis (the vertical axis) does have a scale and this indicates the units of measurement. The bars can be drawn either vertically or horizontally depending upon the number of categories and length or complexity of the category. Draw a Bar Chart Let us create a bar chart in SVG using D3. For this example, we can use the rect elements for the bars and text elements to display our data values corresponding to the bars. To create a bar chart in SVG using D3, let us follow the steps given below. Step 1 − Adding style in the rect element − Let us add the following style to the rect element. svg rect { fill: gray; } Step 2 − Add styles in text element − Add the following CSS class to apply styles to text values. Add this style to SVG text element. It is defined below − svg text { fill: yellow; font: 12px sans-serif; text-anchor: end; } Here, Fill is used to apply colors. Text-anchor is used to position the text towards the right end of the bars. Step 3 − Define variables − Let us add the variables in the script. It is explained below. <script> var data = [10, 5, 12, 15]; var width = 300, scaleFactor = 20, barHeight = 30; </script> Here, Width − Width of the SVG. Scalefactor − Scaled to a pixel value that is visible on the screen. Barheight − This is the static height of the horizontal bars. Step 4 − Append SVG elements − Let us append SVG elements in D3 using the following code. var graph = d3.select(“body”) .append(“svg”) .attr(“width”, width) .attr(“height”, barHeight * data.length); Here, we will first select the document body, create a new SVG element and then append it. We will build our bar graph inside this SVG element. Then, set the width and height of SVG. Height is calculated as bar height * number of data values. We have taken the bar height as 30 and data array length is 4. Then SVG height is calculated as barheight* datalength which is 120 px. Step 5 − Apply transformation − Let us apply the transformation in bar using the following code. var bar = graph.selectAll(“g”) .data(data) .enter() .append(“g”) .attr(“transform”, function(d, i) { return “translate(0,” + i * barHeight + “)”; }); Here, each bar inside corresponds with an element. Therefore, we create group elements. Each of our group elements needs to be positioned one below the other to build a horizontal bar chart. Let us take a transformation formula index * bar height. Step 6 − Append rect elements to the bar − In the previous step, we appended group elements. Now add the rect elements to the bar using the following code. bar.append(“rect”) .attr(“width”, function(d) { return d * scaleFactor; }) .attr(“height”, barHeight – 1); Here, the width is (data value * scale factor) and height is (bar height – margin). Step 7 − Display data − This is the last step. Let us display the data on each bar using the following code. bar.append(“text”) .attr(“x”, function(d) { return (d*scaleFactor); }) .attr(“y”, barHeight / 2) .attr(“dy”, “.35em”) .text(function(d) { return d; }); Here, width is defined as (data value * scalefactor). Text elements do not support padding or margin. For this reason, we need to give it a “dy” offset. This is used to align the text vertically. Step 8 − Working example − The complete code listing is shown in the following code block. Create a webpage barcharts.html and add the following changes. barcharts.html Live Demo <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> <style> svg rect { fill: gray; } svg text { fill: yellow; font: 12px sans-serif; text-anchor: end; } </style> </head> <body> <script> var data = [10, 5, 12, 15]; var width = 300 scaleFactor = 20, barHeight = 30; var graph = d3.select(“body”) .append(“svg”) .attr(“width”, width) .attr(“height”, barHeight * data.length); var bar = graph.selectAll(“g”) .data(data) .enter() .append(“g”) .attr(“transform”, function(d, i) { return “translate(0,” + i * barHeight + “)”; }); bar.append(“rect”).attr(“width”, function(d) { return d * scaleFactor; }) .attr(“height”, barHeight – 1); bar.append(“text”) .attr(“x”, function(d) { return (d*scaleFactor); }) .attr(“y”, barHeight / 2) .attr(“dy”, “.35em”) .text(function(d) { return d; }); </script> </body> </html> Now request your browser, you will see the following response. Circle Chart A Circle chart is a circular statistical graphic, which is divided into slices to illustrate a numerical proportion. Draw a Circle Chart Let us create a circle chart in SVG using D3. To do this, we must adhere to the following steps − Step 1 − Define variables − Let us add the variables in the script. It is shown in the code block below. <script> var width = 400; var height = 400; var data = [10, 20, 30]; var colors = [”green”, ”purple”, ”yellow”]; </script> Here, Width − width of the SVG. Height − height of the SVG. Data − array of data elements. Colors − apply colors to the circle elements. Step 2 − Append SVG elements − Let us append SVG elements in D3 using the following code. var svg = d3.select(“body”) .append(“svg”) .attr(“width”, width) .attr(“height”, height); Step 3 − Apply transformation − Let
D3.js – Transition
D3.js – Transition ”; Previous Next Transition is the process of changing from one state to another of an item. D3.js provides a transition() method to perform transition in the HTML page. Let us learn about transition in this chapter. The transition() method The transition() method is available for all selectors and it starts the transition process. This method supports most of the selection methods such as – attr(), style(), etc. But, It does not support the append() and the data() methods, which need to be called before the transition() method. Also, it provides methods specific to transition like duration(), ease(), etc. A simple transition can be defined as follows − d3.select(“body”) .transition() .style(“background-color”, “lightblue”); A transition can be directly created using the d3.transition() method and then used along with selectors as follows. var t = d3.transition() .duration(2000); d3.select(“body”) .transition(t) .style(“background-color”, “lightblue”); A Minimal Example Let us now create a basic example to understand how transition works. Create a new HTML file, transition_simple.html with the following code. <!DOCTYPE html> <html> <head> <script type = “text/javascript” src = “https://d3js.org/d3.v4.min.js”></script> </head> <body> <h3>Simple transitions</h3> <script> d3.select(“body”).transition().style(“background-color”, “lightblue”); </script> </body> </html> Here, we have selected the body element and then started transition by calling the transition() method. Then, we have instructed to transit the background color from the current color, white to light blue. Now, refresh the browser and on the screen, the background color changes from white to light blue. If we want to change the background color from light blue to gray, we can use the following transition − d3.select(“body”).transition().style(“background-color”, “gray”); Print Page Previous Next Advertisements ”;