What is D3?
It is a tool for data visualization in the browser, making use of the widely implemented Scalable Vector Graphics (SVG), JavaScript, HTML5, and Cascading Style Sheets (CSS3) standards.
Manupulates attributes of DOM elements with the attributes of data items.
Another HTML element, except you can not put another HTML element inside an SVG.
Does not support common HTML attributes or styles such as position, left, top, right, bottom or float.
Interesting fact: if a properly specified value is provided for rx but not for ry (or the opposite), then the browser will consider the missing value equal to the defined one.
M - move.
L - line.
z - close path.
Text
Look at me, I am a text.
Unless you set the style of the SVG text, it inherits font-styles from CSS.
Group
jsFiddle
Any transformations (positioning, scaling, rotating) that are applied to the group element will also be applied to each of the child elements.
SVG allows graphical objects to be defined for later reuse. It is recommended that, wherever possible, referenced elements be defined inside of a defs element. Defining these elements inside of a defs element promotes understandability of the SVG content and thus promotes accessibility. Graphical elements defined in a defs will not be directly rendered. You can use a element to render those elements wherever you want on the viewport.
black
red
blue
jsFiddle
The use element takes nodes from within the SVG document, and duplicates them somewhere else. The effect is the same as if the nodes were deeply cloned into a non-exposed DOM, and then pasted where the use element is, much like cloned template elements in HTML5. Since the cloned nodes are not exposed, care must be taken when using CSS to style a use element and its hidden descendants. CSS attributes are not guaranteed to be inherited by the hidden, cloned DOM unless you explicitly request it using CSS inheritance.
SVG attributes
background-color ==> fill
border ==> stroke
More here
How to D3
Procedure to associate data with DOM
Select a parent container and child nodes
Bind array of data to child nodes
Append nodes to parent container
Bind events, style and animate!
The central principle of D3 design is to enable the programmer to first use a CSS-style selector to select a given set of (DOM) nodes, then use operators to manipulate them in a similar manner to jQuery.
Large datasets can be easily bound to SVG objects using simple D3 functions to generate rich text/graphic charts and diagrams. The data can be in various formats, most commonly JSON, comma-separated values (CSV) or geoJSON.
jQuery
var paragraphs = $("div p");
D3
var paragraphs = d3.select("div").selectAll("p");
jsFiddle
D3 difference: child nodes might not actually exist.
Selectors in D3 are declared the same way as CSS rules. An important difference is that a D3 selector object only contains the elements that matched the selection rule when the selection was first created.
The selection can be based on tag, class, identifier, attribute, or place in the hierarchy. This includes getting and setting attributes, display texts, and styles. Elements may also be added and removed. This process of modifying, creating and removing HTML elements can be made dependent on data, which is the basic concept of D3.js.
Data
Bind array of data to child nodes
d3.selectAll("p")
.data([3, 7, 21, 31, 35, 42])
JSFiddle
Enter() and Append()
d3.select("body").selectAll("p")
.data([3, 7, 21, 31, 35, 42])
.enter().append("p");
JSFiddle
When data is bound to a selection, each element in the data array is paired with the corresponding node in the selection. If there are fewer nodes than data, the extra data elements form the enter selection, which you can instantiate by appending to the enter selection.
D3 methods returns the selection they act upon, you can apply multiple operations to the same selection.
IMPORTANT!There is a gotcha with method chaining, however: while most operations return the same selection, some methods return a new one! For example, selection.append returns a new selection containing the new elements. This conveniently allows you to chain operations into the new elements.
Exit() and Remove()
var bars = d3.select('svg').selectAll('rect').data(someData);
//if we have more data, add new rectangles for those data items
bars.enter().append('rect')
//if we have less data points, remove the rectangles that no longer have a data pairing.
bars.exit().remove();
Using D3’s exit and remove, you can get rid of outgoing nodes that are no longer needed.
if you forget about the enter and exit selections, you will automatically select only the elements for which there exists corresponding data.
// Update…
var p = d3.select("body").selectAll("p")
.data([3, 7, 21, 31, 35, 42]);
// Enter…
p.enter().append("p")
// Exit…
p.exit().remove();
By handling these three cases separately, you specify precisely which operations run on which nodes.
Chaining
d3.select("body").selectAll("p")
.data([3, 7, 21, 31, 35, 42])
.enter().append("p")
.exit().remove();
jsFiddle
while most operations return the same selection, some methods return a new one! For example, selection.append returns a new selection containing the new elements. This conveniently allows you to chain operations into the new elements.
Since method chaining can only be used to descend into the document hierarchy, use var to keep references to selections and go back up.
You can operate over the nodes in a declarative way using selector methods.
setting attributes or styles
registering event listeners
adding, removing or sorting nodes
and changing HTML or text content
Style
You can use data values or index in a callback to define any property.
d3.select("div").selectAll("p").style("color", function(data, i) {
return i % 2 ? "red" : "blue";
});
JSFiddle
Transition
d3.selectAll("circle")
.attr("r", "0");
.transition()
.duration(750)
.delay(function(d, i) { return i * 10; })
.attr("r", function(d) { return Math.sqrt(d); });
Advanced D3
Scales and Domains
Axis
Loading external data
Scales
Scales transform a number in a certain interval (called the domain) into a number in another interval (called the range).
d3.scale.linear - construct a linear quantitative scale.
domain - get or set the scale's input domain.
range - get or set the scale's output range.
Quantitative Scale
Linear scales
Logarithmic scales
Power scales (including square root scales)
var x = d3.scale.linear()
.domain([0, d3.max(data)])// your data minimum and maximum
.range([0, 420]);//the pixels to map to
d3.select(".chart")
.selectAll("div")
.data([3, 7, 21, 31, 35, 42])
.enter().append("div")
.style("width", function(d) { return x(d) + "px"; })
JSFiddle
Ordinal Scale
Ordinal Scale have a discrete domain, such as a set of names or categories.
var x = d3.scale.ordinal()
.domain(["A", "B", "C", "D", "E", "F"])
.rangeRoundBands([0, width], .1);
d3.scale.category10() - Constructs a new ordinal scale with a range of ten categorical colors:
JSFiddle
Axis
d3.svg.axis creates a new axis generator.
axis.scale
axis.orient
axis.ticks
axis.tickFormat
var xAxis = d3.svg.axis()
.scale(x)
.orient('bottom')
.tickValues(data);
JSFiddle
d3.time.format - creates a new local time formatter for a given specifier.
d3.time.format("%Y-%m-%d");
JSFiddle
d3.time.scale - constructs a linear time scale.
var xScale = d3.time.scale()
.domain([2009-07-13T00:02, 2009-07-13T23:48])
.rangeRound([0, width]);
//rangeRound does the same thing as range but rounds the values to integers or begining of dates.
JSFiddle
d3.time.intervals - a time interval in local time.
d3.time.hour
d3.time.week
d3.time.monday
d3.time.year
Working with Arrays
Most commonly used functions
d3.min/d3.max
d3.range
d3.keys - lists the keys of an associative array.
d3.merge - merges multiple arrays into one array.
d3.nest - groups array elements hierarchically.
jsFiddle
Loading External Resources
Don't forget to put the functions inside the async function.
THE END
BY Aysegul Yonet / aysegulyonet@gmail.com