Skip to content

Instantly share code, notes, and snippets.

@phoebebright
Created July 6, 2012 09:14
Show Gist options
  • Save phoebebright/3059149 to your computer and use it in GitHub Desktop.
Save phoebebright/3059149 to your computer and use it in GitHub Desktop.
d3 sortKeys in nest function

Shows behaviour of sortkeys and that date sort is sorting by the string value of the date.

See it running at http://bl.ocks.org/3059149

<html>
<head>
<title>D3 Simple Nest Example</title>
<script src="http://d3js.org/d3.v2.js"></script>
</head>
<body>
<script>
// expected date format in csv file
var in_format = d3.time.format("%Y-%m-%d");
d3.csv("./nest1.csv", function(csv_data){
// coerce csv data into correct formats
csv_data.forEach(function(line) {
line.time = parseInt(line.time);
line.date = in_format.parse(line.date);
})
// now create one array for each unique group
var nested_data = d3.nest()
.key(function(d) { return d.group; })
.entries(csv_data);
console.debug(nested_data);
alert('Key: group, Sort:None\n'+dump(nested_data));
/*
OR nest by date
*/
var nested_data = d3.nest()
.key(function(d) { return d.date; })
.entries(csv_data);
console.debug(nested_data);
alert('Key: date, Sort:None\n'+dump(nested_data));
// ADD sortKeys
var nested_data = d3.nest()
.key(function(d) { return d.date; })
.sortKeys(d3.ascending)
.entries(csv_data);
console.debug(nested_data);
alert('Key: date, Sort:ascending\nEXPECTING TO BE SORTED BY DATE'+dump(nested_data));
/*
OR nest by time
*/
var nested_data = d3.nest()
.key(function(d) { return d.time; })
.entries(csv_data);
console.debug(nested_data);
alert('Key: time, Sort:None\n'+dump(nested_data));
// ADD sortKeys
var nested_data = d3.nest()
.key(function(d) { return d.time; })
.sortKeys(d3.ascending)
.entries(csv_data);
console.debug(nested_data);
alert('Key: time, Sort:ascending\n'+dump(nested_data));
});
function dump(arr,level) {
// from this page: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
var dumped_text = "";
if(!level) level = 0;
//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += " ";
if(typeof(arr) == 'object') { //Array/Hashes/Objects
for(var item in arr) {
var value = arr[item];
if(typeof(value) == 'object') { //If it is an array,
dumped_text += level_padding + "'" + item + "':\n";
dumped_text += dump(value,level+1);
} else {
dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}
</script>
</body>
</html>
group date time
one 2012-01-01 4
one 2012-01-01 6
two 2012-01-06 3
three 2012-01-01 4
three 2012-01-05 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment