Reputation: 648
Data
newdata = [
{'Name':'Andrew', 'Country':'US', 'Start date':'2012-7-2','Total':'30days'
}, {'Name':'Kat', 'Country':'US', 'Start date':'2012-2-2','Total':'24days'
}, {'Name':'Barry', 'Country':'France', 'Start date':'2012-12-2','Total':'22days'
}, {'Name':'Ash', 'Country':'US', 'Start date':'2015-2-2','Total':'20days'
}, {'Name':'Lucy', 'Country':'UK', 'Start date':'2016-2-2','Total':'35days'
}, {'Name':'Gerry', 'Country':'US', 'Start date':'2016-2-2','Total':'40days'
}, {'Name':'Alex', 'Country':'France', 'Start date':'2016-2-2','Total':'28days'
}, {'Name':'Morgan', 'Country':'UK', 'Start date':'2012-6-2','Total':'24days'
}];
I would like to be able to create a group for each different 'Country' (3 in total) and then to populate each of the groups with the 'Name' belonging to them.
My question is how can I return the unique names for 'Country' to create the groups?
I've had success creating the 3 groups using d3.map() when binding the data but this stripped out the rest of the values
https://jsfiddle.net/hellococomo/3d1asL4d/2/
Code
var canvas = d3.select('#chart')
.append('svg')
.attr('width', 350)
.attr('height', 600)
.append('g')
.attr('transform', 'translate(0,20)')
var country = canvas
.selectAll(".country")
.data(newdata)
var countryEnter = country
.enter().append("g")
.attr('class', 'country')
countryEnter
.append("text")
.attr('class', 'name')
country.select('.name')
.text(function(d, i) {
return d.Country;
})
.attr('y', function(d, i) {
return i * 30;
});
UPDATE
Nesting worked for me. As Cyril suggested, I used d3.nest() to create keys from 'Country'. I also decided to use div and p here instead of svg:g
New working code
var nested_data = d3.nest()
.key(function(d) { return d.Country; })
.entries(newdata);
console.log(nested_data)
var canvas = d3.select('#chart')
.attr('width', 350)
.attr('height', 600)
.attr('transform', 'translate(0,20)')
var country = canvas
.selectAll(".country")
.data(nested_data)
var countryEnter = country
.enter().append('div')
.attr('class', 'country')
countryEnter
.append("p")
.attr('class', 'label')
.style('font-weight', 'bold')
.text(function(d, i) {
return d.key;
})
countryEnter.selectAll('.name')
.data(function(d) {
return d.values;
})
.enter().append('p')
.attr('class', 'name')
.text(function(d) {
return d.Name;
})
Upvotes: 1
Views: 885
Reputation: 32327
You can group your data using nest
var nested_data = d3.nest()
.key(function(d) { return d.Country; })
.entries(newdata);
console.log(nested_data)
Hope this helps!
This should help you more http://bl.ocks.org/phoebebright/raw/3176159/
Upvotes: 1