About
Whether you’re building a static chart or a dynamic one with fluid transitions and object constancy, your code remains roughly the same.
See also: D3 - HTML Template
Steps
Add a new element - Basic
var body = d3.select("body"); // Select the first "body" node.
var p = body.append("div"); // Append an P element as a child of the "body" node.
p.html("Hello World!"); // Add the text "Hello World!" in the p element content
where:
- The D3 object is the start point of D3 to access its methods.
Add a new element - Method chaining style
D3 supports method chaining. Selection methods, such as selection.attr, return the current selection.
d3
.select("body")
.append("div")
.html("Hello World!");
Since method chaining can only be used to descend into the document hierarchy, use var to keep references to selections and go back up.
var section = d3.select("body").append("section");
section.append("div")
.html("First!");
section.append("div")
.html("Second!");
Binding Data - Data Join
The data join is a general pattern that can be used to create, update or destroy elements whenever data changes.
We will do a node selection that is empty. Therefore the returned update and exit selections of the data join (the data function) are also empty. We only need to handle the enter selection which represents the new data without existing element. We instantiate these missing elements by appending them to the enter selection.
.chart div {
font: 10px sans-serif;
background-color: steelblue;
text-align: right;
padding: 3px;
margin: 1px;
color: white;
}
var data= [ 4, 8, 15, 16, 23, 42 ];
d3.select("body") // We need to get an element
.append("div").classed("chart", true) // We add the chart graph container element (The div .chart element)
.selectAll("div") // We select all div but we will get a null selection because their is no div element
.data(data) // We join the empty selection with the data
.enter() // Their is no data, therefore only the enter set of the data join contains nodes without element
.append("div") // We append for each data a div element with the below style
.style("width", function(d) { return d * 10 + "px"; })
.text(function(d) { return d; });
The div .chart element acts as a chart container that lets you position and style the chart without affecting the rest of the page.
D3’s selection operators such as attr, style and property allow to specify the value either as:
- a constant (the same for all selected elements)
- or a function (computed separately for each element).