block by hugolpz 824446bb2f9bc8cce607

.data() vs .datum()

Full Screen

This project aim to illustrate with code the similarities and differences between .data() and .datum(). Feel free to fork and add other parallel examples, where .data() and .datum() do the same work with different syntaxes.

.data() and .datum()‘s generated elements are taggued and get collored accordingly using CSS class) :

.data:hover  { fill: #B10000; opacity: 1; } /*  data = RED   */
.datum:hover { fill: #00B100; opacity: 1; } /*  datum= GREEN */


Given data such:

var json = [
    {"x":,"y":,"name":"John", "scores": [2,12,7]},
    {"x":,"y":,"name":"Jean", "scores": [4,10,6]},
    {"x":,"y":,"name":"Jack", "scores": [8, 6,2]}

The number of elements in your data array should match the number of elements in the selection. To bind your json elements to a single SVG element, wrap in an array:

var chart ="body").append("svg")
    .attr("class", "chart")

Or [selection.datum][3] without data-joins:

var chart ="body").append("svg")
    .attr("class", "chart")

to create multiple SVG elements then use data-joins :

var chart ="body").selectAll("svg")
    .attr("class", "chart")

var rect = chart.selectAll("rect")
    .data(function(d) { return d.scores; })

Simple English

Both are ways to join data.

.datum([values[, key]]) rather for static datavizualisation not needing updates, binds data directly into an element to inject without computing a join.

.data([value]) : Joins the specified array of data with the current selection. The specified value is an array of data values, such as an array of numbers [1,4,3,6] or objects [{ "x":3,"y":2},{ "x":2,"y":5}] or a function that returns an array of values, such function(d) { return d.scores; }.

Binds data-joins and add a generalisation allowing interactive dataviz by providing 3 sets :

To read