Skip to content

Instantly share code, notes, and snippets.

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>
<script src='' type='text/javascript'></script>
<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));
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()
.rangeRoundBands([height, 0], .9);
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56"]);
var svg ='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++) {
.attr('class', 'path')
.attr('stroke', 'black')
.attr('stroke-width', 1)
.attr('opacity', 0.8)
.style('fill', color(j))
.attr('d', d3.svg.area()
.x(function(d, i) { return x(i); })
.y0(function(d) { return y(j) - d/2; })
.y1(function(d) { return y(j) + d/2; })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment