I'm new to D3 and playing around with a scatterplot. I cannot get d3.max(data) to work correctly in setting up domain!
I have the following setting up a random dataset:
var data = [];
for (i=0; i < 40; i++){
data.push({"x": i/40, "y": i/8, "a": Math.floor(Math.random() * 3), "x2": Math.random()});
}
And then the following to set my coordinates:
var x = d3.scale.linear().domain([0, 1]).range([0 + margin, w-margin]),
y = d3.scale.linear().domain([0, d3.max(data)]).range([0 + margin, h-margin]),
c = d3.scale.linear().domain([0, 3]).range(["hsl(100,50%,50%)", "rgb(350, 50%, 50%)"]).interpolate(d3.interpolateHsl);
This puts all 40 points in a single, horizontal line. If I replace d3.max(data) with '5' then it is a diagonal (albeit from the upper left to the bottom right, I'm still struggling to flip y-coordinates). Why isn't d3.max(data) working as expected?
d3.max()
expects an array of numbers, not of objects. The elements of data
have an internal key-value structure and there is no way for d3.max()
to know what to take the maximum of. You can use something like jQuery's $.map
to get the elements of the objects you want and then take the max, e.g.
var maxy = d3.max($.map(data, function(d) { return d.y; }));
Edit:
As pointed out in the comment below, you don't even need JQuery for this, as .map()
is a native Array method. The code then becomes simply
var maxy = d3.max(data.map(function(d) { return d.y; }));
or even simpler (and for those browsers that don't implement Array.map()
), using the optional second argument of d3.max
that tells it how to access values within the array
var maxy = d3.max(data, function(d) { return d.y; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With