Skip to content

Instantly share code, notes, and snippets.

@jstcki
Created March 18, 2013 17:23
Show Gist options
  • Save jstcki/5189018 to your computer and use it in GitHub Desktop.
Save jstcki/5189018 to your computer and use it in GitHub Desktop.
D3 Data Tutorial
require("http://d3js.org/d3.v3.js");
var data = [{"id":"ARE","pop":7890924,"country_name":"United Arab Emirates"},
{"id":"ARG","pop":40764561,"country_name":"Argentina"},
{"id":"AUS","pop":22620600,"country_name":"Australia"}];
// How many items are in the data?
var dataCount = data.length;
// Sort an array
data.sort(function(a, b) { return a.pop - b.pop; })
// Or the other way around ...
data.sort(function(a, b) { return b.pop - a.pop; })
// Oooor use D3 comparators ...
data.sort(function(a, b) { return d3.ascending(a.pop, b.pop); })
data.sort(function(a, b) { return d3.descending(a.pop, b.pop); })
// How do we find the maximum population in the data?
d3.max(data, function(d) {
return d.pop;
});
d3.min(data, function(d) {
return d.pop;
});
// Min and max values combined!
d3.extent(data, function(d) {
return d.pop;
});
// Then you can use that information as domain
var x = d3.scale.linear() // or .log()?
.domain([0, d3.max(data, function(d) {
return d.pop;
})])
.range([0, 100]);
// rangeBands()?????
// array.map(fn) returns a new array where each item
// is mapped to the return value of fn.
// I.e. we here extract all the country ids and use them as domain
var idsOnly = data.map(function(d) { return d.id; });
idsOnly;
var y = d3.scale.ordinal()
.domain(idsOnly)
// As output range we want evenly spaced bands from 20 to 600
//with a padding of 0.1 (relative to the band width) between them
.rangeBands([20, 600], 0.1);
y("ARG")
y("AUS")
y("ARE")
// Transform syntax
"translate(100,50)rotate(90)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment