D3.js Basics

By Xah Lee. Date: . Last updated: .

d3 learning notes.

can select things.

d3.selectAll

d3.selectAll("p").style("color", "white");

Yet, you can still manipulate individual nodes as needed:

d3.select

d3.select("body").style("background-color", "black");

can also style things.

note that style is a method of whatever those select returns.

so, this means, those select must return some d3 object.

d3.select("body").append("p").text("hi!");
d3.selectAll("p").style("color", "pinnk");
d3.select("body").style("background-color", "black");
// For example, to randomly color paragraphs:
d3.selectAll("p").style("color", function() {
  return "hsl(" + Math.random() * 360 + ",100%,50%)";
});
// To alternate shades of gray for even and odd nodes:
d3.selectAll("p").style("color", function(d, i) {
  return i % 2 ? "#fff" : "#eee";
});
d3.selectAll("p")
    .data([1,2,6,9])
    .style("font-size", function(x) { return x + "px"; });

binding data

one big thing about d3 is binding data to elements.

d3 is designed with the idea of data in, and visual stuff out.

binding data to element basically means, set data as a property of a object (a DOM element object). [see JS: Property Overview]

typically done like this

d3.select(…).data(…)

d3 enter

very strange thing.

d3.select("body").selectAll("p")
d3.select("body").selectAll("p")
    .data(mydata)
    .enter()
    .append("p")
    .text("tttt!");

The data is stored as property to element as __data__


d3 select or selectAll. can be nested, e.g.

d3.select("#x40").selectAll("div")

that means, its properly implemented as a obect, the d3 object, and there is a property “selection”, e.g. d3.selection, whose value is dom. Initially, the default value is document (or null). When a selection method is called, it checks if it's null, if so, target it as document. Else, use its value d3.selection as selection target.

Check if the above is true.


.data() returns a a object that represents “update selection”

https://github.com/d3/d3-selection/blob/master/README.md#selection_data

it also has enter and exit methods.

https://github.com/d3/d3-selection/blob/master/README.md#selection_enter


find out if d3.select, when no result, does it actually auto create them. Seems so.

If you have a question, put $5 at patreon and message me.