Reputation: 545
I am trying to get the extent of my xy-data which has this nested form:
data = [
{"points": [{"x": 0, "y": 0}, {"x": -5, "y": 100}, {"x": 300, "y": 1}, ...],
"rgbval": "rgb(0, 0, 0)"
},
{"points": [{"x": 1, "y": 2}, {"x": -7000, "y": 2}, {"x": 0, "y": 0}, ...],
"rgbval": "rgb(255, 0, 0)"
},
.
.
.
]
In the case of this sample data, the values I'm looking for are:
x_domain = [-7000, 300]
y_domain = [0, 100]
I am able to get the extent of a particular group of points using:
for i in [0...data.length]
console.log(d3.extent(data[i].points, (d) -> d.x)) # x_domain of i_th group of points
console.log(d3.extent(data[i].points, (d) -> d.y)) # y_domain of i_th group of points
In the sample case, this would give me two x_domains and two y_domains. I want the domains of the overall xy data.
Upvotes: 4
Views: 210
Reputation: 102198
First, merge the arrays using d3.merge (which is pretty much a fancy concat
):
var merged = d3.merge(data.map(function(d){ return d.points}));
Then, just get the extent the normal way:
var xExtent = d3.extent(merged, function(d){ return d.x});
var yExtent = d3.extent(merged, function(d){ return d.y});
Here is the demo:
var data = [{
"points": [{
"x": 0,
"y": 0
}, {
"x": -5,
"y": 100
}, {
"x": 300,
"y": 1
}],
"rgbval": "rgb(0, 0, 0)"
}, {
"points": [{
"x": 1,
"y": 2
}, {
"x": -7000,
"y": 2
}, {
"x": 0,
"y": 0
}],
"rgbval": "rgb(255, 0, 0)"
}];
var merged = d3.merge(data.map(function(d) {
return d.points
}));
var xExtent = d3.extent(merged, function(d) {
return d.x
});
var yExtent = d3.extent(merged, function(d) {
return d.y
});
console.log("x extent: " + xExtent);
console.log("y extent: " + yExtent);
<script src="https://d3js.org/d3.v4.min.js"></script>
PS: don't mistake this uncommon d3.merge
for the way more famous selection.merge
.
Upvotes: 4