Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
d3 way to handle 3D array

In the middle of this script is a for loop that iterates over the arrays in the 3D data array. There must be a more d3ish way of doing this than using a javascript for loop, but I can't figure out how to retain each row's index position in the larger array to pass to the y() scaling function.

<!DOCTYPE html>
<html>
<head>
<title>hi</title>
<script src='http://d3js.org/d3.v2.min.js' type='text/javascript'></script>
</head>
<body>
<script type='text/javascript'>
var width = 900;
var height = 400;
// generate random data into five arrays
var data = [];
for (var i=0; i<5; i++) {
var a = [];
for (var j=0; j<90; j++) {
a.push(Math.floor(Math.random() * 100));
}
data.push(a);
};
var x = d3.scale.linear()
.domain([d3.min(data, function (d) { return d3.min(d); }),
d3.max(data, function (d) { return d3.max(d); } )])
.range([0, width]);
var y = d3.scale.ordinal()
.domain(d3.range(data.length))
.rangeRoundBands([height, 0], .9);
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56"]);
var svg = d3.select('body').append('svg')
.attr('width', width)
.attr('height', height);
// this is the bit i want to replace. what's the d3 way?
for (var j=0; j<data.length; j++) {
svg.selectAll('path.area')
.data([data[j]])
.enter().append('path')
.attr('class', 'path')
.attr('stroke', 'black')
.attr('stroke-width', 1)
.attr('opacity', 0.8)
.style('fill', color(j))
.attr('d', d3.svg.area()
.interpolate('bundle')
.x(function(d, i) { return x(i); })
.y0(function(d) { return y(j) - d/2; })
.y1(function(d) { return y(j) + d/2; })
);
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.