Data Visualization

Part 2: D3.js – Playing with Data


First of all, some basics As I promised in Part 1.  D3.js is more beautiful with data, after all it makes sense to make cool visualizations with data , ultimately real value comes ouf of working with data. Data visualizations that makes data sensible to us. 

Little bit on D3 Selectors

One of the things that I love about D3 is its W3C standard-compliant (HTML,SVG, CSS). You can control the SVG elements styles thru external stylesheets. Modern browsers Chrome,Firefox,Opera are bringing new features from W3C specs and you get that out of the box with D3.js. It’s not reinventing the wheel and that’s what I like about D3.js

D3 Selectos uses W3C DOM Selectors API and it says:

The Selectors API specification defines methods for retrieving Element nodes from the DOM by matching against a group of selectors.”

You can select the elements by 
  • tag (“tag”) , 
  • class (“.class”),
  • element id (“#id”), attribute
  • (“[name=value]”), 
  • containment (“parent child”), 
  • adjacency (“before after”),
 
and various other facets. Predicates can be intersected (“.a.b”)
or unioned (“.a, .b”), resulting in a rich but concise selection method.

Let’s get to some real stuff now. When you use d3,  its not required to build data visualizations with SVG only, you can work with normal HTML elements as well, however when you are talking hundreds and thousand of millions of records for data visualizations with filters and animations,  SVG will blow you with results


Bring in some data,  dude!!!

HTML:
 
<!DOCTYPE html>
<html>
<head>
<title>Hello, Bar Charts!!!</title>
<scripttype=“text/javascript”src=“d3.v2.js”></script>
<linkrel=“stylesheet”type=“text/css”href=“hellod3.css”>
</head>
<body>
<scripttype=“text/javascript”>
var dataset = [];                        
for (var i = 0; i <50; i++) {
 
//Generate random number (0-35)  
        
 var randomNumber = Math.random() * 35;  
 dataset.push(randomNumber);             
}
d3.select(“body”).selectAll(“div”)
    .data(dataset)
    .enter()
    .append(“div”)
    .attr(“class”, “bar”)
    .style(“height”, function(d) {
    var barHeight = d * 5;  //its all about height , calculation matters 
    return barHeight + “px”;
});    
</script>
</body>
</html>
 
CSS
 
div.bar {
    display: inline-block;
    width: 20px;
    height: 75px;   /*Initial height, */
    background-color: teal;
    margin-right: 2px;
}
 
Let’s understand the code now
 
 
 
d3.select – we are selecting body element and selecting all “div” elements and binding with .data (dataset).  Notice here d3 is making use of method chaining and data() is smart enough to loop thru all array elements and applying CSS style at the same time. This is the real power. Your visualization can be complex,  but power of data() will amaze you.
Its very important to understand how visualization work in web browser. D3 does this very cleanly, 
Using D3’s enter and exit selections, you can create new nodes for incoming data and remove outgoing nodes that are no longer needed.
d3.enter it creates placeholder nodes for incoming data.

Its rather important to understand d3.exit() at the same time

d3.exitit removes existing DOM elements in the current selection for which no new data element was found

 

(Image Courtesy:vis.stanford.edu/files/2011-D3-InfoVis.pdf)

Output:

Notice the dataset variable in your Javascript console

Ok, in Part3 I am going cover how to draw with SVG with some animations and will explore more on data()
 
Have fun!!!

 

 
 
Advertisements

Introduction to D3 – Part 1: Hello D3!!!


Everyday is a new day and it brings you new surprises. For me, it came in form of D3.js at Data Visualization Toronto Meetup and amazed by it. It gets more interesting with crossfilter and dc.js – which I will leave it for future posts

Data Driven Document (D3).js is a data visualization library for web created by Michael Bostock, Vadim Ogievetsky and Jeffrey Heer.  Without wasting any further time, let’s start with basics. D3.js alllows you to  manipulate documents based on data. D3 helps you bring data to life using HTML, SVG and CSS.

In order to work with D3 you need to understand Javascript Objects, functions and the method-chaining paradigm of JQuery. A basic understanding of SVG, CSS will go a long way.
Let’s start with 

SVG (Scalable Vector Graphics)
SVG images and their behaviors are defined in XML text files. This means that they can be searched, indexed, scripted, and, if need be, compressed. As XML files, SVG images can be created and edited with any text editor, but it is often more convenient to create them with drawing programs (source:wiki)

SVG specification is developed by W3C and here’s the most basic explanation of it

Scalable – means to increase or decrease uniformly. In terms of graphics, scalable means not being limited to a single, fixed, pixel size.
Vector graphics contain geometric objects such as lines and curves.

Graphics Most existing XML grammars represent either textual information, or represent raw data such as financial information. They typically provide only rudimentary graphical capabilities, often less capable than the HTML ‘img’ element. SVG fills a gap in the market by providing a rich, structured description of vector and mixed vector/raster graphics; it can be used stand-alone, or as an XML namespace with other grammars.

SVG provides basics shapes like rect,circle,ellipse,line,polyline,polygon

<svg xmlns=”http://www.w3.org/2000/svg&#8221; version=”1.1″>
<circle cx=”50″ cy=”70″ r=”40″ fill=”red” />
</svg>
Now, we are done with SVG basics let’s start with an example
We need
  • A browser and a web server (for Mac/Linux users: there is one build in your machine, just start python -m SimpleHTTPServer 8888 in Terminal Window and the current path becomes ‘server’) . For windows user Apache Tomact or nginx [engine x] would also work
  • Download d3.js (comes with samples, some of them will NOT run when you open the html files as file, so use the web server instead!)
  • Text editor

<!DOCTYPE html>
<html>
<head>
<title>Hello, D3!!!</title>
<script type="text/javascript" src="lib/d3.js"></script>
</head>
<body>
<div id="dvto"></div>
<script type="text/javascript">

var vizSVG = d3.select(“#dvto")
.append("svg:svg")
.attr("width", 100)
.attr("height", 100);

vizSVG.append("svg:circle")
.style("stroke", "black")
.style("fill", "red")
.attr("r", 40)
.attr("cx", 100)
.attr("cy", 50)

</script>
</body>
</html>


Here's the output

 


D3 employs a declarative approach, operating on arbitrary sets of nodes called selections. So every DOM element is essentially a selector as show above.
Equivalent SVG Source of above
<svg xmlns=”http://www.w3.org/2000/svg&#8221; version=”1.1″>
<circle cx=”100″ cy=”50″ r=”40″ stroke=”black”
fill=”red”/>
</svg>
That’s it for now, have fun!!  I will go more deep into D3, Crossfilter concepts  and explain dc.js (Dimensional Charting) in upcoming posts in Part2 and onwards