Reputation: 1196
I am new to d3 and trying to plot some data in one box for each of four specific states, similar to this page but with states not continents, and a lot more data points. I have a json dataset of more than 42,000 entries supposedly from just those 4 states.
To key by state, I used this:
d3.json("data/business.json",function(json) {
var data=d3.nest()
.key(function(d) {return d.state;})
.sortKeys(d3.ascending)
.entries(json);
Then later make one box for each state:
// One cell for each state
var g=svg.selectAll("g").data(data).enter()
.append("g")
(attributes, etc)
Fine, but I soon found that the dataset includes some data from several states I don't want to consider so it was plotting more boxes than I wanted.
I would like a way to exclude the data that isn't from the four states without altering the original data file. What is the best way to go about this?
Upvotes: 1
Views: 795
Reputation: 7990
It's possible to filter the output from d3.nest rather than the original array:
function trim(nested, f) {
return nested
.filter(function (e) {
return f(e.key)
})
.map(function (e) {
if (e && (typeof e =='object') && Array.isArray(e.values) && ('key' in e)) {
return { key: e.key, values: trim(e.values, f)}
}
else return e
})
}
For instance:
function isNewEngland(st) {
return ["ME","VT","NH","MA", "CT", "RI"].indexOf(st)>=0
}
data = trim(data, isNewEngland)
Upvotes: 0
Reputation: 109242
Filter your json
:
var keep = ["state1", "state2", "state3", "state4"];
json = json.filter(function(d) { return keep.indexOf(d.state) > -1; });
Upvotes: 1