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 = d3.select("body").append("svg")
.data([json])
.attr("class", "chart")
…
Or [selection.datum][3] without data-joins:
var chart = d3.select("body").append("svg")
.datum(json)
.attr("class", "chart")
…
to create multiple SVG elements then use data-joins :
var chart = d3.select("body").selectAll("svg")
.data(json)
.enter()
.append("svg")
.attr("class", "chart")
…
var rect = chart.selectAll("rect")
.data(function(d) { return d.scores; })
.enter().append("rect")
…
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 :
.enter()
, output the set of graphic elements for which no data exists any longer, aka enter
.data()
(make update), output the set of elements for which the data is updated, aka update
.exit()
, output the set of elements for which no data item existed before, aka exit
.append()
, check all the 3 sets above, append the new elements with their values.Official:
Modified http://code.jquery.com/jquery-2.0.2.min.js to a secure url
Modified http://d3js.org/d3.v3.min.js to a secure url
Modified http://d3js.org/topojson.v1.min.js to a secure url
https://code.jquery.com/jquery-2.0.2.min.js
https://d3js.org/d3.v3.min.js
https://d3js.org/topojson.v1.min.js