Selecting and filtering data points
This page is about finding the data points behind the elements. You can also select visible elements.
From an event
In the function from the event, use d
.
d3.selectAll("circle")
.data(datapoints)
.enter().append("circle")
.on('click', function(d) {
console.log('You clicked');
console.log(d.country);
})
By a filter
From your complete set of datapoints, you just filter out everything you don’t want
Get all American data points
var americanPoints = datapoints.filter( function(d) {
return d.country == 'America';
})
Get all data points of people older than 24 but younger than 45
var selectedPeople = datapoints.filter( function(d) {
return d.age > 24 && d.age < 45;
})
Sorting data points
Use the .sort
method of the data array. It takes a
and b
and a comparison function. Subtraction is an easy way to get the “right” result, but you can also check out a longer description.
// make sure you aren't using function(d) here!
var sorted = datapoints.sort(function(a, b) {
return a.age - b.age;
});
Selecting nearest data point to mouse on axis
You can read about how this works on the select visible elements page.
.on('mousemove', function() {
// invert the scale to go from PIXELS to YEARS
var mouse = d3.mouse(this);
var mouseYear = xPositionScale.invert(mouse[0]);
// find the index of the data point closest to that year in the dataset
var index = d3.bisector(function(d) { return d.year; })
.left(datapoints, mouseYear);
var datapoint= datapoints[index];
console.log("The closest data point is ", datapoint);
})
From inside groups with d3.nest
+ click (or any other event)
You group with d3.nest
, then bind your nested data. Once you interact with the object, you use d.values
to get the elements inside of that group.
var nested = d3.nest()
.key( function(d) { return d.state; })
.entries(datapoints);
d3.selectAll(".states")
.data(nested)
.enter().append("circle")
.on('click', function(d) {
console.log("The name is", d.key);
console.log("The cities are:");
console.log(d.values)
})
From inside groups with d3.nest
WITHOUT an event
This time you only have the name of the state you’re interested in – “New York” – instead of having someone click the New York circle. It’s a little more complicated.
var nested = d3.nest()
.key( function(d) { return d.state; })
.entries(datapoints);
You just use .filter
and take the first result.
javascript
// .filter gives you an array, then the [0] takes the first result
var newyork = nested.filter(function(d) { return d.key == "New York"; })[0];