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 ofdatahave an internal key-value structure and there is no way ford3.max()to know what to take the maximum of. You can use something like jQuery’s$.mapto get the elements of the objects you want and then take the max, e.g.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 simplyor even simpler (and for those browsers that don’t implement
Array.map()), using the optional second argument ofd3.maxthat tells it how to access values within the array