DC.js – Heat Map ”; Previous Next A Heat Map is a graphical representation of data in the form of a map, in which data values are represented as colors. This chapter explains about a heat map in detail. Before moving on to draw a heat map, we should understand the dc.heatMap class and its methods. The dc.heatMap uses mixins to get the basic functionality of drawing a chart, which are listed below − dc.colorMixin dc.marginMixin dc.baseMixin The complete class diagram of the dc.heatMap is as follows − The dc.heatMap gets all the methods of the above-specified mixins. It has its own methods to draw the heat map, which are explained below − boxOnClick( [handler]) This method is used to get or set the handler, when an individual cell is clicked in the heatmap. cols( [cols]) This method is used get or set the keys to create the columns of the heatmap. colsLabel( [label]) This method is used to get or set the column label, which is represented as the column name. Similarly, we can perform a row label as well. rows( [rows]) This method is used to get or set the values used to create the rows of the heatmap. xAxisOnClick( [handler]) This method is used to get or set the handler, when a column tick is clicked in the x-axis. xBorderRadius( [border]) This method is used to set the X border radius. If the value is set to 0, then you will get full rectangles. Draw a Heatmap Let us draw a heatmap in DC. To do this, we need to follow the steps given below − Step 1: Define a variable Let us define a variable as shown below − var chart = dc.heatMap(”#heatmap”); Here, the heatMap function is mapped with the id heatmap. Step 2: Read the data Read the data from the howell1.csv file as shown below − d3.csv(“data/howell1.csv”, function(errors, people) { var mycrossfilter = crossfilter(people); } Here, we have used the same howell1.csv file and it looks as shown below − “height”,”weight”,”age”,”male” 151.765,47.8256065,63,1 139.7,36.4858065,63,0 136.525,31.864838,65,0 156.845,53.0419145,41,1 145.415,41.276872,51,0 163.83,62.992589,35,1 149.225,38.2434755,32,0 168.91,55.4799715,27,1 147.955,34.869885,19,0 165.1,54.487739,54,1 154.305,49.89512,47,0 …………………. …………………. Step 3: Fetch the records Let us fetch the records using the coding given below − people.forEach(function(x) { x.age = Math.floor(x.age) + 1; x.heightRange = Math.floor(x.height / 10) + 1; x.weightRange = Math.floor(x.weight / 10) + 1; if(x.male == 1) { x.gender = 1; } else { x.gender = 2; } }); Here, we have checked the gender and have set the height and width range of the x-axis by using the above formula. Step 4: Set the dimension You can set the dimension using the coding given below − var ageDimension = mycrossfilter.dimension(function(data) { return [+data.gender, +data.heightRange]; }); After the dimension has been assigned, group the gender using the coding given below − var genderGroup = genderDimension.group().reduceCount(); Step 5: Generate a chart Now, generate a heatmap using the coding given below − chart .width(20 * 45 + 80) .height(2 * 45 + 40) .dimension(ageDimension) .group(ageGroup) .keyAccessor(function(d) { return +d.key[1]; }) .valueAccessor(function(d) { return +d.key[0]; }) .colorAccessor(function(d) { return +d.value; }) .title(function(d) { return “Height Range: ” + ((d.key[1] – 1) * 10) + ” – ” + (d.key[1] * 10) + “cmn” + “Gender: ” + (d.key[0] == 1 ? “Male” : “Female”) + “n” + “Count: ” + (d.value) + ” count”; }) .calculateColorDomain() chart.render(); }); Here, We have assigned the chart width as 20 × 45 + 80 and height as 2 × 45 + 40. Then we have assigned the gender dimension and group. Key and value accessor returns the key and value from the heatmaps. We have to use the colorAccessor() function to return the color. Finally, set the title and render the chart. Step 6: Working example The complete coding is as follows. Create a web page heatmap.html and add the following changes to it. <html> <head> <title>DC heat map Sample</title> <link rel = “stylesheet” type = “text/css” href = “css/bootstrap.css”> <link rel = “stylesheet” type = “text/css” href = “css/dc.css”/> <script src = “js/d3.js”></script> <script src = “js/crossfilter.js”></script> <script src = “js/dc.js”></script> </head> <body> <div> <div id = “heatmap”></div> </div> <script language = “javascript”> var chart = dc.heatMap(”#heatmap”); d3.csv(“data/howell1.csv”, function(errors, people) { var mycrossfilter = crossfilter(people); people.forEach(function(x) { x.age = Math.floor(x.age) + 1; x.heightRange = Math.floor(x.height / 10) + 1; x.weightRange = Math.floor(x.weight / 10) + 1; if(x.male == 1) { x.gender = 1; } else { x.gender = 2; } }); var ageDimension = mycrossfilter.dimension(function(data) { return [+data.gender, +data.heightRange]; }); var ageGroup = ageDimension.group().reduceCount(); chart .width(20 * 45 + 80) .height(2 * 45 + 40) .dimension(ageDimension) .group(ageGroup) .keyAccessor(function(d) { return +d.key[1]; }) .valueAccessor(function(d) { return +d.key[0]; }) .colorAccessor(function(d) { return +d.value; }) .title(function(d) { return “Height Range: ” + ((d.key[1] – 1) * 10) + ” – ” + (d.key[1] * 10) + “cmn” + “Gender: ” + (d.key[0] == 1 ? “Male” : “Female”) + “n” + “Count: ” + (d.value) + ” count”;}) .calculateColorDomain() chart.render(); }); </script> </body> </html> Now, request the browser and we will see the following response. Print Page Previous Next Advertisements ”;
Category: dcjs
DC.js – Bar Chart
DC.js – Bar Chart ”; Previous Next Bar chart is 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. The graph is constructed such 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. Bar Chart Methods Before moving to draw a bar chart, we should understand the dc.barChart class and its methods. The dc.barChart uses mixins to get the basic functionality of drawing a chart. The mixins used by the dc.barChart are as follows − dc.stackMixin dc.coordinateGridMixin The complete class diagram of the dc.barChart is as follows − The dc.barChart gets all the methods of the above specified mixins. In addition, it also has its own methods to draw the bar chart. They are explained as follows − alwaysUseRounding( [round]) This method is used to get or set whether rounding is enabled when the bars are centered. barPadding( [pad]) This method is used to get or set the spacing between bars as a fraction of bar size. The possible padding values are between 0-1. centerBar( [centerBar]) This method is used to set the bar, centered around the data position on the x-axis. gap( [gap]) This method is used to set a fixed gap between the bars. outerPadding( [pad]) This method is used to set the outer padding on an ordinal bar chart. Draw a Bar Chart Let us draw a bar chart in DC. To do this, we should follow the steps given below − Step 1: Define a variable Let us define a chart variable as shown below − var chart = dc.barChart(”#bar”); Here, the dc.barChart function is mapped with a container having bar as the id. Step 2: Read the data Read data from the people.csv file. d3.csv(“data/people.csv”, function(errors, people) { var mycrossfilter = crossfilter(people); } If the data is not present, then it returns an error. Now, assign the data to Crossfilter. For this example, we will use the same people.csv file, which looks as follows − id,name,gender,DOB,MaritalStatus,CreditCardType 1,Damaris,Female,1973-02-18,false,visa-electron 2,Barbe,Female,1969-04-10,true,americanexpress 3,Belia,Female,1960-04-16,false,maestro 4,Leoline,Female,1995-01-19,true,bankcard 5,Valentine,Female,1992-04-16,false, 6,Rosanne,Female,1985-01-05,true,bankcard 7,Shalna,Female,1956-11-01,false,jcb 8,Mordy,Male,1990-03-27,true,china-unionpay ……………… ……………… ……………… Step 3: Create an age dimension Now, create a dimension for age as shown below − var ageDimension = mycrossfilter.dimension(function(data) { return ~~((Date.now() – new Date(data.DOB)) / (31557600000)) }); Here, we assigned the age from the Crossfilter data. The ~~ is a double NOT bitwise operator. It is used as a faster substitute for the Math.floor() function. Now, group it using the reduceCount() function that is shown below − var ageGroup = ageDimension.group().reduceCount(); Step 4: Generate a chart Now, generate a bar chart using the coding given below − chart .width(800) .height(300) .x(d3.scale.linear().domain([15,70])) .brushOn(false) .yAxisLabel(“Count”) .xAxisLabel(“Age”) .dimension(ageDimension) .group(ageGroup) .on(”renderlet”, function(chart) { chart.selectAll(”rect”).on(”click”, function(d) { console.log(”click!”, d); }); }); chart.render(); Here, Chart width is 800 and height is 300. The d3.scale.linear function is used to construct a new linear scale with the specified domain range [15, 70]. Next, we set the brushOn value to false. We assign the y-axis label as count and x-axis label as age. Finally, group the age using the ageGroup function. Step 5: Working example The complete code listing is as follows. Create a web page bar.html and add the following changes to it. <html> <head> <title>DC Bar chart Sample</title> <link rel = “stylesheet” type = “text/css” href = “css/bootstrap.min.css”> <link rel = “stylesheet” type = “text/css” href = “css/dc.css”/> <script src = “js/d3.js”></script> <script src = “js/crossfilter.js”></script> <script src = “js/dc.js”></script> </head> <body> <div> <div id = “bar”></div> </div> <script language = “javascript”> var chart = dc.barChart(”#bar”); d3.csv(“data/people.csv”, function(errors, people) { var mycrossfilter = crossfilter(people); var ageDimension = mycrossfilter.dimension(function(data) { return ~~((Date.now() – new Date(data.DOB)) / (31557600000)) }); var ageGroup = ageDimension.group().reduceCount(); chart .width(800) .height(300) .x(d3.scale.linear().domain([15,70])) .brushOn(false) .yAxisLabel(“Count”) .xAxisLabel(“Age”) .dimension(ageDimension) .group(ageGroup) .on(”renderlet”, function(chart) { chart.selectAll(”rect”).on(”click”, function(d) { console.log(”click!”, d); }); }); chart.render(); }); </script> </body> </html> Now, request the browser and we will see the following response. Print Page Previous Next Advertisements ”;
DC.js – Concepts
DC.js – Concepts ”; Previous Next DC.js is simple and easy for most front-end developers. It enables building basic charts quickly, even without any knowledge of D3.js. Before, we start using DC.js to create visualization; we need to get familiar with web standards. The following web standards are heavily used in D3.js, which is the foundation of DC.js for rendering charts. Hypertext Markup Language (HTML) Document Object Model (DOM) Cascading Style Sheets (CSS) Let us understand each of these web standards 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”. A typical basic HTML example looks like as shown below − <!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 make 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 such as SVG or XHTML). CSS describes how elements should be rendered on a webpage. 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 specification as well as other features, which are not based on ECMAScript standards. JavaScript knowledge is a prerequisite for DC.js. Components DC.js is based on two excellent JavaScript libraries, which are − Crossfilter D3.js Crossfilter Crossfilter is a JavaScript library for exploring large multivariate datasets in the browser. It is used for Grouping, Filtering, and Aggregating tens or hundreds of thousands of rows of raw data very quickly. D3.js D3.js stands for Data-Driven Documents. D3.js is a JavaScript library for manipulating documents based on data. D3 is Dynamic, Interactive, Online Data Visualizations Framework and used in large number of websites. D3.js is written by Mike Bostock, created as a successor to an earlier visualization toolkit called Protovis. D3.js is used on hundreds of thousands of websites. Print Page Previous Next Advertisements ”;
DC.js – Data Grid
DC.js – Data Grid ”; Previous Next Data grid is used to filter and display the records. This chapter explains about data grid in detail. Data Grid Methods Before moving on to draw a data grid, we should understand the dc.dataGrid class and its methods. This class uses a mixin to get the basic functionality of drawing a data grid chart, which is defined below − dc.baseMixin The dc.dataGrid gets all the methods of this mixin as well as has its own methods to draw the data grid, which is explained below − beginSlice( [slice]) This method is used to get or set the index of the beginning slice. This method is useful when implementing pagination. Similarly, you can perform endSlice(). group(function) This method is used to perform the group function for the data grid. html( [html]) This method is used to get or set the function to generate a dynamic html. order( [order]) It is used to sort the order function. size( [size]) It is used to display the number of items in the grid. sortBy( [sortByFunction]) This method is used to get or set the sort-by function. We can sort a particular field using this function. For example: we can sort by age, which is defined below − chart.sortBy(function(d) { return d.age; }); Data Grid Example Let us perform a data grid in DC. To do this, we need to follow the steps given below − Step 1: Add styles Let us add styles in CSS using the coding below − .dc-chart { font-size: 12px; } .dc-grid-top { padding-left: 10px; font-size: 14px; font-weight: bold; } .dc-grid-item { padding-left: 10px; font-size: 12px; font-weight: normal; } Here, we have assigned the styles for the chart, grid-top and grid-item. Step 2: Create a variable Let us create a variable in DC as explained below − var barChart = dc.barChart(”#line”); var countChart = dc.dataCount(“#mystats”); var gridChart = dc.dataGrid(“#mygrid”); Here, we have assigned a barChart variable id in line, countChart id is mystats and gridChart id is mygrid. Step 3: Read the data Read the data from the people.csv file as shown below − d3.csv(“data/people.csv”, function(errors, people) { var mycrossfilter = crossfilter(people); } If data is not present, then it returns an error. Now, assign the data to a crossfilter. Here, we used the same people.csv file, which was used in our previous charting examples. It looks like as shown below − id,name,gender,DOB,MaritalStatus,CreditCardType 1,Damaris,Female,1973-02-18,false,visa-electron 2,Barbe,Female,1969-04-10,true,americanexpress 3,Belia,Female,1960-04-16,false,maestro 4,Leoline,Female,1995-01-19,true,bankcard 5,Valentine,Female,1992-04-16,false, 6,Rosanne,Female,1985-01-05,true,bankcard 7,Shalna,Female,1956-11-01,false,jcb 8,Mordy,Male,1990-03-27,true,china-unionpay …………………………………… ………………………………….. Step 4: Set the dimension You can set the dimension using the coding given below − var ageDimension = mycrossfilter.dimension(function(data) { return ~~((Date.now() – new Date(data.DOB)) / (31557600000)) }); After the dimension has been assigned, group the age using the coding given below − var ageGroup = ageDimension.group().reduceCount(); Step 5: Generate a chart Now, generate a bar chart using the coding given below − barChart .width(400) .height(200) .x(d3.scale.linear().domain([15,70])) .yAxisLabel(“Count”) .xAxisLabel(“Age”) .elasticY(true) .elasticX(true) .dimension(ageDimension) .group(ageGroup); Here, We have assigned the chart width as 400 and height as 200. Next, we have specified the domain range as [15,70]. We have set the x-axis label as age and y-axis label as count. We have specified the elasticY and X function as true. Step 6: Create the grid chart Now, create the grid chart using the coding given below − gridChart .dimension(ageDimension) .group(function (data) { return ~~((Date.now() – new Date(data.DOB)) / (31557600000)); }) Step 7: Render the grid Now, render the grid using the coding given below − .size(100) .htmlGroup (function(d) { return ”Age: ” + d.key + ”; Count: ” + d.values.length + ” people” }) .html (function(d) { return d.name; }) .sortBy(function (d) { return d.name; }) .order(d3.ascending); barChart.render(); countChart.render(); gridChart.render(); Here, we have sorted the name using the html() function and have finally rendered the chart. Step 8: Working example The complete code is as follows. Create a webpage datagrid.html and add the following changes to it. <html> <head> <title>DC datagrid sample</title> <link rel = “stylesheet” type = “text/css” href = “css/bootstrap.css”> <link rel = “stylesheet” type = “text/css” href = “css/dc.css”/> <style> .dc-chart { font-size: 12px; } .dc-grid-top { padding-left: 10px; font-size: 14px; font-weight: bold; } .dc-grid-item { padding-left: 10px; font-size: 12px; font-weight: normal; } </style> <script src = “js/d3.js”></script> <script src = “js/crossfilter.js”></script> <script src = “js/dc.js”></script> </head> <body> <div> <div style = “width: 600px;”> <div id = “mystats” class = “dc-data-count” style = “float: right”> <span class = “filter-count”></span> selected out of <span class = “total-count”></span> | <a href = “javascript:dc.filterAll(); dc.renderAll();”>Reset All</a> </div> </div> <div style = “clear: both; padding-top: 20px;”> <div> <div id = “line”></div> </div> </div> <div style = “clear: both”> <div class = “dc-data-grid” id = “mygrid”></div> </div> </div> <script language = “javascript”> var barChart = dc.barChart(”#line”); var countChart = dc.dataCount(“#mystats”); var gridChart = dc.dataGrid(“#mygrid”); d3.csv(“data/people.csv”, function(errors, people) { var mycrossfilter = crossfilter(people); // age dimension var ageDimension = mycrossfilter.dimension(function(data) { return ~~((Date.now() – new Date(data.DOB)) / (31557600000)) }); var ageGroup = ageDimension.group().reduceCount(); barChart .width(400) .height(200) .x(d3.scale.linear().domain([15,70])) .yAxisLabel(“Count”) .xAxisLabel(“Age”) .elasticY(true) .elasticX(true) .dimension(ageDimension) .group(ageGroup); countChart .dimension(mycrossfilter) .group(mycrossfilter.groupAll()); gridChart .dimension(ageDimension) .group(function (data) { return ~~((Date.now() – new Date(data.DOB)) / (31557600000)); }) .size(100) .htmlGroup (function(d) { return ”Age: ” + d.key + ”; Count: ” + d.values.length + ” people” }) .html (function(d) { return d.name; }) .sortBy(function (d) { return d.name; }) .order(d3.ascending); barChart.render(); countChart.render(); gridChart.render(); }); </script> </body> </html> Now, request the browser and we will see the following response. Initially, the grid chart looks like the following screenshot. If you select a particular age between 63 and 66, it filters out the following records. Print Page Previous Next Advertisements ”;
DC.js – Bubble Chart
DC.js – Bubble Chart ”; Previous Next A bubble chart is used to display three dimensions of the data. It is a variation of scatter chart, in which the data points are replaced with bubbles. The bubble sizes are represented with respect to the data dimension. It uses horizontal and vertical axes as value axes. This chapter explains about bubble chart in detail. Bubble Chart Methods Before moving on to draw a bubble chart, we should understand the dc.bubbleChart class and its methods. The dc.bubbleChart uses mixins to get the basic functionality of drawing a chart, which are listed below − dc.bubbleMixin dc.coordinateGridMixin The complete class diagram of the dc.bubbleChart is as follows − The dc.bubbleChart gets all the methods of the above-specified mixins. It also has its own methods to draw the bubble chart, which are explained below − elasticRadius( [radius]) This method is used to enable the bubble radius. If we disable this, then the bubble radius will be rescaled automatically. sortBubbleSize( [sortBubbleSize]) This method is used to enable the sorting feature in bubbles. Smaller bubbles will come first and then they gradually increase. Draw a Bubble Chart Let us draw a bubble chart in DC. To do this, we need to follow the steps given below − Step 1: Define a variable Let us define a variable as shown below − var chart = dc.bubbleChart(”#bubble”); Here, the bubbleChart function is mapped with the id bubble. Step 2: Read the data Read data from the howell1.csv file. d3.csv(“data/howell1.csv”, function(errors, people) { var mycrossfilter = crossfilter(people); } If data is not present, then it returns an error. Now, assign the data to a crossfilter. Here, we have already downloaded the howell1.csv file. The same file will be used here and it will look similar to the following code block. “height”,”weight”,”age”,”male” 151.765,47.8256065,63,1 139.7,36.4858065,63,0 136.525,31.864838,65,0 156.845,53.0419145,41,1 145.415,41.276872,51,0 163.83,62.992589,35,1 149.225,38.2434755,32,0 168.91,55.4799715,27,1 147.955,34.869885,19,0 165.1,54.487739,54,1 154.305,49.89512,47,0 ……………….. ………………… Step 3: Fetch the records Let us fetch the records using the coding given below − people.forEach(function(x) { if(x.male == 1) { x.gender = “Male”; } else { x.gender = “Female”; } x.heightRange = (((Math.floor(x.height / 10)) + 1) * 10); x.weightRange = (((Math.floor(x.weight / 10)) + 1) * 10); }); Here, we have checked the gender and have set the x-axis height and width range using the above formula. Step 4: Set the dimension We can set the dimension using the coding given below − var genderDimension = mycrossfilter.dimension(function(data) { return [ data.gender, data.heightRange, data.weightRange ]; }); After the dimension has been assigned, group the gender using the coding given below − var genderGroup = genderDimension.group().reduceCount(); Step 5: Generate the chart Now, generate a bubble chart using the coding given below − chart.width(1200) .height(400) .margins({top: 10, right: 50, bottom: 30, left: 60}) .dimension(genderDimension) .group(genderGroup) .keyAccessor(function (p) { return p.key[1]; }) .valueAccessor(function (p) { return p.key[2]; }) .radiusValueAccessor(function (p) { return (Math.floor((p.value / 10)) + 1); }) Here, We have assigned the chart width as 1200 and the height as 400. Next, we have specified the margin points. Then we have assigned the gender dimension and group. Key and value accessor returns the key and value from the bubbles. Calculate the radius value accessor function using the formula – Math.floor((p.value / 10)) + 1. Step 6: Draw bubbles Now, draw the bubbles using the coding given below − .x(d3.scale.linear().domain([0, 240])) .y(d3.scale.linear().domain([-40, 120])) .r(d3.scale.linear().domain([0, 20])) .minRadiusWithLabel(1000) .yAxisPadding(100) .xAxisPadding(200) .maxBubbleRelativeSize(0.07) .renderHorizontalGridLines(true) .renderVerticalGridLines(true) .renderLabel(true) .renderTitle(true) .title(function (p) { return p.key[0] + “n” + “Height: ” + p.key[1] + ” cmn” + “Weight: ” + p.key[2] + ” kgn” + “Count: ” + p.value; }); Here, The d3.scale.linear function is used to construct a new linear scale with the specified domain range [0,240] for the x-axis. Similarly, we assigned y and radius linear scale values. We specified the minimum radius label value as 1000, x-axis and y-axis padding values as 200 and 100 respectively. Next, we have specified a maximum bubble relative size value as 0.7. Render the horizontal and vertical grid lines, then map with the title for bubble key and values. Step 7: Set TickFormat Set the ticket formats for x and y-axis using the coding given below − chart.yAxis().tickFormat(function (s) { return s + ” cm”; }); chart.xAxis().tickFormat(function (s) { return s + ” kg”; }); Finally, render the chart using the chart.render() method. Step 8: Working example The complete code listing is as shown in the following code block. Create a web page bubble.html and add the following changes to it. <html> <head> <title>Bubble chart Sample</title> <link rel = “stylesheet” type = “text/css” href = “css/bootstrap.css”> <link rel = “stylesheet” type = “text/css” href = “css/dc.css”/> <script src = “js/d3.js”></script> <script src = “js/crossfilter.js”></script> <script src = “js/dc.js”></script> </head> <body> <div> <div id = “bubble”></div> </div> <script language = “javascript”> var chart = dc.bubbleChart(”#bubble”); d3.csv(“data/howell1.csv”, function(errors, people) { var mycrossfilter = crossfilter(people); people.forEach(function(x) { if(x.male == 1) { x.gender = “Male”; } else { x.gender = “Female”; } x.heightRange = (((Math.floor(x.height / 10)) + 1) * 10); x.weightRange = (((Math.floor(x.weight / 10)) + 1) * 10); }); var genderDimension = mycrossfilter.dimension(function(data) { return [ data.gender, data.heightRange, data.weightRange ]; }); var genderGroup = genderDimension.group().reduceCount(); chart.width(1200) .height(400) .margins({top: 10, right: 50, bottom: 30, left: 60}) .dimension(genderDimension) .group(genderGroup) .keyAccessor(function (p) { return p.key[1]; }) .valueAccessor(function (p) { return p.key[2]; }) .radiusValueAccessor(function (p) { return (Math.floor((p.value / 10)) + 1); }) .x(d3.scale.linear().domain([0, 240])) .y(d3.scale.linear().domain([-40, 120])) .r(d3.scale.linear().domain([0, 20])) .minRadiusWithLabel(1000) .yAxisPadding(100) .xAxisPadding(200) .maxBubbleRelativeSize(0.07) .renderHorizontalGridLines(true) .renderVerticalGridLines(true) .renderLabel(true) .renderTitle(true) .title(function (p) { return p.key[0] + “n” + “Height: ” + p.key[1] + ” cmn” + “Weight: ” + p.key[2] + ” kgn” + “Count: ” + p.value; }); chart.yAxis().tickFormat(function (s) { return s + ” cm”; }); chart.xAxis().tickFormat(function (s) { return s + ” kg”; }); chart.render(); }); </script> </body> </html> Now, request the browser and we will see the following response. Print Page Previous Next Advertisements ”;
DC.js – Line Chart
DC.js – Line Chart ”; Previous Next A line chart is used to display information as a series of data points connected by straight lines. A data point represents two values, one plotted along the horizontal axis and another along the vertical axis. For example, the popularity of food items can be drawn as a line chart in such a way that the food item is represented along the x-axis and its popularity is represented along the y-axis. This chapter explains about line charts in detail. Line Chart Methods Before moving on to draw a line chart, we should understand the dc.lineChart class and its methods. The dc.lineChart uses mixins to get the basic functionality of drawing a chart. The mixins used by dc.lineChart are as follows − dc.stackMixin dc.coordinateGridMixin The complete class diagram of the dc.lineChart is as follows − The dc.lineChart gets all the methods of the above-specified mixins as well as it has its own methods to draw the line chart. They are explained as follows. dashStyle( [style]) This method is used to set the dash style for a line chart. dotRadius( [radius]) This method is used to get or set the radius (in PX) for dots displayed on the data points. It is defined as follows − chart.dotRadius = function (radius) { if (!arguments.length) { return radius; } }; interpolate( [i]) This method is used to get or set the interpolator for a line. renderArea( [area]) This method is used to get or set the render area. renderDataPoints( [options]) This method is used to render individual dots for each data point. tension( [tension]) This method is used get or set the tension for the lines drawn. It is in the range from 0 to 1. xyTipsOn( [xyTipsOn]) This method is used to change the mouse behavior of an individual data point. Draw a Line Chart Let us draw a line chart in DC. To do this, we need to follow the steps given below − Step 1: Define a variable Let us define a variable as shown below − var chart = dc.lineChart(”#line”); Here, the dc.linechart function is mapped with the container having an id line. Step 2: Read the data Read data from the people.csv file − d3.csv(“data/people.csv”, function(errors, people) { var mycrossfilter = crossfilter(people); } Here, if we used the same dataset people.csv, the sample data file will be as follows − id,name,gender,DOB,MaritalStatus,CreditCardType 1,Damaris,Female,1973-02-18,false,visa-electron 2,Barbe,Female,1969-04-10,true,americanexpress 3,Belia,Female,1960-04-16,false,maestro 4,Leoline,Female,1995-01-19,true,bankcard 5,Valentine,Female,1992-04-16,false, 6,Rosanne,Female,1985-01-05,true,bankcard 7,Shalna,Female,1956-11-01,false,jcb 8,Mordy,Male,1990-03-27,true,china-unionpay …………… ……………. ……………. Step 3: Create an age dimension Now, create dimension for age as shown below − var ageDimension = mycrossfilter.dimension(function(data) { return ~~((Date.now() – new Date(data.DOB)) / (31557600000)) }); Here, we assigned the age from the Crossfilter data. The ~~ is a double NOT bitwise operator. It is used as a faster substitute for the Math.floor() function. Now, group it using the reduceCount() function, which is defined below − var ageGroup = ageDimension.group().reduceCount(); Step 4: Generate a chart Now, generate a line chart using the coding given below − chart .width(800) .height(300) .x(d3.scale.linear().domain([15,70])) .brushOn(false) .yAxisLabel(“Count”) .xAxisLabel(“Age”) .dimension(ageDimension) .group(ageGroup) .on(”renderlet”, function(chart) { chart.selectAll(”rect”).on(”click”, function(d) { console.log(”click!”, d); }); }); chart.render(); Here, Chart width is 800 and height is 300. The d3.scale.linear function is used to construct a new linear scale with the specified domain range [15, 70]. Next, we set the brushOn value to false. We assign the y-axis label as count and x-axis label as age. Finally, group the age using ageGroup. Step 5: Working example The complete code listing is shown in the following code block. Create a web page line.html and add the following changes to it. <html> <head> <title>DC.js Line Chart Sample</title> <link rel = “stylesheet” type = “text/css” href = “css/bootstrap.min.css”> <link rel = “stylesheet” type = “text/css” href = “css/dc.css”/> <script src = “js/d3.js”></script> <script src = “js/crossfilter.js”></script> <script src = “js/dc.js”></script> </head> <body> <div> <div id = “line”></div> </div> <script language = “javascript”> var chart = dc.lineChart(”#line”); d3.csv(“data/people.csv”, function(errors, people) { var mycrossfilter = crossfilter(people); var ageDimension = mycrossfilter.dimension(function(data) { return ~~((Date.now() – new Date(data.DOB)) / (31557600000)) }); var ageGroup = ageDimension.group().reduceCount(); chart .width(800) .height(300) .x(d3.scale.linear().domain([15,70])) .brushOn(false) .yAxisLabel(“Count”) .xAxisLabel(“Age”) .dimension(ageDimension) .group(ageGroup) .on(”renderlet”, function(chart) { chart.selectAll(”rect”).on(”click”, function(d) { console.log(”click!”, d); }); }); chart.render(); }); </script> </body> </html> Now, request the browser and we will see the following response. Print Page Previous Next Advertisements ”;
DC.js – Composite Chart
DC.js – Composite Chart ”; Previous Next Composite chart is a special type of chart provided by DC.js. It provides an option to render multiple charts in the same coordinate grid. Composite chart enables advanced chart visualization options with a minimum line of code. Composite Chart Methods Before moving on to draw a composite chart, we need to understand the dc.compositeChart class and its methods. The dc.compositeChart uses mixins to get the basic functionality of drawing a chart. The mixins used by the dc.compositeChart are as follows − dc.baseMixin dc.marginMixin dc.colorMixin dc.coordinateGridMixin The complete class diagram of the dc.barChart is as follows − The dc.compositeChart gets all the methods of the above-specified mixins. It has its own method to draw the composite chart, which is explained below − compose( [subChartArray]) Set the collection of charts to be rendered in the same coordinate grid chart. chart.compose([ dc.lineChart(chart) dc.barChart(chart) ]); children() Gets all the charts composed in the same coordinate grid. childOptions( [childOptions]) Gets or sets the chart options for all the child charts composed in the same coordinate grid. shareTitle( [shareTitle]) Gets or sets the shared title of the chart. If set, it will be shared with all the children charts composed in the same coordinate grid. shareColors( [shareColors]) Similar to the shareTitle() function, except it shares the colors instead of the title. rightY( [yScale]) Gets or sets the y-scale for the right axis of the composite chart. rightYAxis( [rightYAxis]) Gets or sets the right y-axis of the composite chart. rightYAxisLabel( rightYAxisLabel[??]) Gets or sets the right y-axis label. alignYAxes( [alignYAxes]) Gets or sets the alignment between the left and right y-axis. useRightAxisGridLines( [useRightAxisGridLines]) Gets or sets whether to draw gridlines from the right y-axis of the composite chart. The default behavior is to draw from the left y-axis. Draw a Composite Chart Let us draw a composite chart using DC.js. To do this, we should follow the steps given below − Step 1: Define a variable Let us define a chart variable as shown below − var chart = dc.compositeChart(”#compoiste”); Here, the dc.compositeChart function is mapped with a container having composite as its id. Step 2: Read the data Read data from the people.csv file − d3.csv(“data/people.csv”, function(errors, people) { } If data is not present, then it returns an error. We will use the same people.csv file. The sample data file is as follows − id,name,gender,DOB,MaritalStatus,CreditCardType 1,Damaris,Female,1973-02-18,false,visa-electron 2,Barbe,Female,1969-04-10,true,americanexpress 3,Belia,Female,1960-04-16,false,maestro 4,Leoline,Female,1995-01-19,true,bankcard 5,Valentine,Female,1992-04-16,false, 6,Rosanne,Female,1985-01-05,true,bankcard 7,Shalna,Female,1956-11-01,false,jcb 8,Mordy,Male,1990-03-27,true,china-unionpay …………. …………. ………….. Step 3: Map the data Now, map the data as shown below − var ndx = crossfilter(); ndx.add(people.map(function(data) { return { age: ~~((Date.now() – new Date(data.DOB)) / (31557600000)), male: data.gender == ”Male” ? 1 : 0, female: data.gender == ”Male” ? 0 : 1 }; })); Here, we assigned the age from the Crossfilter data. The ~~ is a double NOT bitwise operator. It is used as a faster substitute. Now, apply the dimension age and group the gender data using the coding given below − var dim = ndx.dimension(dc.pluck(”age”)), grp1 = dim.group().reduceSum(dc.pluck(”male”)), grp2 = dim.group().reduceSum(dc.pluck(”female”)); Step 4: Generate a chart Now, generate a composite chart using the coding given below − composite .width(768) .height(480) .x(d3.scale.linear().domain([15,70])) .yAxisLabel(“Count”) .xAxisLabel(“Age”) .legend(dc.legend().x(80).y(20).itemHeight(13).gap(5)) .renderHorizontalGridLines(true) .compose ([ dc.lineChart(composite) .dimension(dim) .colors(”red”) .group(grp1, “Male”) .dashStyle([2,2]), dc.lineChart(composite) .dimension(dim) .colors(”blue”) .group(grp2, “Female”) .dashStyle([5,5]) ]) .brushOn(false) .render(); Here, Chart width is 768 and height is 480. The d3.scale.linear function is used to construct a new linear scale with the specified domain range [15, 70]. We assign a x-axis label as age and y-axis label as count. Next, render horizontal grid lines as true. Compose the line chart colors value – red for male gender and blue for female. Finally, we set the brushOn value to false and render the chart. Step 5: Working example The complete code is as follows. Create a web page composite.html and add the following changes to it. <html> <head> <title>DC composite chart Sample</title> <link rel = “stylesheet” type = “text/css” href = “css/bootstrap.css”> <link rel = “stylesheet” type = “text/css” href = “css/dc.css”/> <script src = “js/d3.js”></script> <script src = “js/crossfilter.js”></script> <script src = “js/dc.js”></script> </head> <body> <div> <div id = “composite”></div> </div> <script type = “text/javascript”> var composite = dc.compositeChart(“#composite”); d3.csv(“data/people.csv”, function(errors, people) { var ndx = crossfilter(); ndx.add(people.map(function(data) { return { age: ~~((Date.now() – new Date(data.DOB)) / (31557600000)), male: data.gender == ”Male” ? 1 : 0, female: data.gender == ”Male” ? 0 : 1 }; })); var dim = ndx.dimension(dc.pluck(”age”)), grp1 = dim.group().reduceSum(dc.pluck(”male”)), grp2 = dim.group().reduceSum(dc.pluck(”female”)); composite .width(768) .height(480) .x(d3.scale.linear().domain([15,70])) .yAxisLabel(“Count”) .xAxisLabel(“Age”) .legend(dc.legend().x(80).y(20).itemHeight(13).gap(5)) .renderHorizontalGridLines(true) .compose ([ dc.lineChart(composite) .dimension(dim) .colors(”red”) .group(grp1, “Male”) .dashStyle([2,2]), dc.lineChart(composite) .dimension(dim) .colors(”blue”) .group(grp2, “Female”) .dashStyle([5,5]) ]) .brushOn(false) .render(); }); </script> </body> </html> Now, request the browser and we will see the following response. Print Page Previous Next Advertisements ”;
DC.js – Discussion
Discuss DC.js ”; Previous Next DC.js is a charting library built on top of D3.js and works natively with crossfilter, which is another popular JavaScript library used to explore millions of records in a short period on the client side. DC.js is a JavaScript library used to make interactive dashboards in JavaScript. This tutorial will give you a complete knowledge on the DC.js framework. This is an introductory tutorial, which covers the basics of DC.js and explains how to deal with its various modules and sub-modules. Print Page Previous Next Advertisements ”;
DC.js – capMixin
DC.js – capMixin ”; Previous Next capMixin enables to group the list of data element below a certain value as ‘Others’. It is applicable in both row and pie charts. The hierarchy of the capMixin is as defined in the diagram below. capMixin provides four methods to find the Others section and they are as follows − Method 1: cap( [count]) − Gets or sets the count of elements that will be included in the cap. Method 2: othersGrouper( [grouperFunction]) − Gets or sets the function to do the ‘Others’ group. The default function provided is as follows. chart.othersGrouper(function (topItems, restItems) { var restItemsSum = d3.sum(restItems, _chart.valueAccessor()), restKeys = restItems.map(_chart.keyAccessor()); if (restItemsSum > 0) { return topItems.concat([{ others: restKeys, key: _chart.othersLabel(), value: restItemsSum }]); } return topItems; }); Method 3: othersLabel( [label]) − Gets or sets the label for ‘Others’ group. Method 4: takeFront( [takeFront]) − Gets or sets the direction of capping. If set, the chart takes the front items from the sorted array of data elements; otherwise it will take the last items. Print Page Previous Next Advertisements ”;
DC.js – baseMixin
DC.js – baseMixin ”; Previous Next baseMixin provides basic methods needed to create any type of a chart. It ranges from setting the width of the chart to advanced filtering of the chart. General Chart Options The basicMixin provides many chart methods to get / set the properties of the charts. They are as follows, chartID() − Returns the internal numeric ID of the chart. chartGroup( [chartGroup]) − Gets or sets the group to which the chart belongs. In DC.js, charts can be grouped into a single set. All charts in a group are expected to share the same Crossfilter dataset. They are rendered as well as redrawn simultaneously. mychart.chartGroup(”dashboard”); minWidth( [minWidth]) − Sets the minimum width of the chart. mychart.minWidth(300); width( [width]) − Gets or sets the width of the chart. mychart.width(600); minHeight( [minHeight]) − Gets or sets the minimum height of the chart. mychart.minHeight(300); height( [height]) − Gets or sets the height of the chart. mychart.height(300); title( [titleFunction]) − Gets or sets the title function. Title is the SVG Element”s title of the child element in the chart (e.g. a single bar in a bar chart). Title in the charts are represented as tooltip in the browser. mychart.title(function(data) { return d.key + ”: ” + d.value; }); label( labelFunction[??]) − Similar to the title() method, but it sets the label instead of the title. mychart.label(function(data) { return d.key + ”: ” + d.value; }); options(opts) − Sets any chart option using the JavaScript object. Each key represents the corresponding method available in the charts and the matched method will be invoked with the relevant value. mychart.options ({ ”width” : 300, ”height” : 300 }); Here, width() and height() method will be fired with the specified value. legend( [legend]) − Attaches a legend to the chart. The legend can be created using the d3.legend() method. mychart.legend ( dc.legend() .x(500) .y(50) .itemHeight(12) .gap(4)) anchor( parent[??]) − Sets the root SVGElement to be either an existing chart”s root or any valid D3 single selectors. Optionally, the chart group can also be set using the second argument. anchorName() − Gets the DOM ID of the chart”s anchored location. svg( [svgElement]) − Returns the SVGElement of the chart. resetSvg() − Resets the SVG container in the DOM. root( [rootElement]) − Gets the root container of the chart. Data Options basicMixin provides methods to set the data for the charts. The data is set as Crossfilter dimension and group. In addition, it provides an option to get the underlying dataset. dimension( [dimension]) − Sets or gets the dimension of the chart. A dimension is any valid Crossfilter dimension. var mycrossfilter = crossfilter([]); var ageDimension = mycrossfilter.dimension(dc.pluck(”age”)); mychart.dimension(ageDimension); group( group[??]) − Sets or gets the group of the chart. A group is any valid Crossfilter group. The group can be named using the second argument to use it later in the code. var mycrossfilter = crossfilter([]); var ageDimension = mycrossfilter.dimension(dc.pluck(”age”)); mychart.dimension(ageDimension); mychart.group(ageDimension.group(crossfilter.reduceCount())); data( [callback]) − Sets the data callback and enables us to get the underlying chart”s data set. // get all groups mychart.data(function (group) { return group.all(); }); // get top five groups mychart.data(function (group) { return group.top(5); }); keyAccessor( [keyAccessor]) − Gets or sets the key accessor function. It is used to retrieve the key from the underlying Crossfilter group. The key is used for slices in a pie chart and x-axis in the line / bar chart. The default key accessor function is as follows − chart.keyAccessor(function(d) { return d.key; }); valueAccessor( [valueAccessor]) − Gets or sets the value accessor function. It is used to retrieve the value from the underlying Crossfilter group. The value is used for slice size in the pie chart and y-axis position in the line / bar chart. The default value accessor function is as follows − chart.valueAccessor(function(d) { return d.value; }); ordering( [orderFunction]) − Gets or sets an ordering function to order ordinal dimension. By default, a chart uses crossfilter.quicksort.by to sort the elements. _chart.ordering(dc.pluck(”key”)); Filter Options Filtering is one of the highlights of DC.js. We can apply one or more filters directly on the chart object using the filter() method and call chart”s redrawGroup() or dc.redrawAll() method to see the filtering effect on the chart. By default, a chart object takes one or more filters using the filter() method, applies it on the underlying Crossfilter() data set, gets the filtered data from the Crossfilter and redraws the charts using the filtered data. DC.js provides the following methods to handle filtering in the chart. Filter( [filter]) Gets or sets the filter for the chart. If a supplied filter is new, then it will be added to the chart”s filter collection and applied on the underlying dataset. If the filter supplied is already available in the chart”s filter collection, then it will remove the filter and do the relevant filtering on the underlying data. In short, filter method will toggle the supplied filters. mychart.filter(10); To remove all filters, call the filter method with null value. The filter may be any one of the following items − null − Chart will remove all the filters previously applied. single value − Chart will call the underlying Crossfilter”s filter method and send the supplied value. dc.filters.RangedFilter − It accepts two values, low and high. Chart will filter out all the data, except the value in the range between low and high value. dc.filters.TwoDimensionalFilter − It accepts two-dimensional values that are used in the heat map. dc.filters.RangedTwoDimensionalFilter − It is similar to the dc.filters.RangedFilter, except that it accepts a two-dimensional value only used in scatter plots. hasFilter( [filter]) Checks whether the supplied filter is available or not in the chart. replaceFilter( [filter]) Replaces the current filter of the chart with the supplied filter. filters() Returns all current filters associated with the chart. filterAll() Clears all filters associated with the chart. filterHandler( [filterHandler]) Gets or sets a filter handler function. Filter handler function is used by the chart to filter the underlying dataset using the filter. Chart has