Accepted answer

I think that generating the data before trying to draw the rectangles is a better approach. You can use d3.range to generate the data matrix:

// Setup
var width = 300,
    height = 300,
    div ='#chart'),
    svg = div.append('svg')
        .attr('width', width)
        .attr('height', height),
    rw = 95,
    rh = 95;  

Where rw and rh are the width and height of the rectangles. Then, you can create the data matrix:

var data = [];
for (var k = 0; k < 3; k += 1) {

To actually draw the rectangles, you can bind the elements of the data array (the inner arrays) to groups in svg, and translate the groups based in the row number, adding a small margin:

// Create a group for each row in the data matrix and translate the 
// group vertically
var grp = svg.selectAll('g')
    .attr('transform', function(d, i) {
        return 'translate(0, ' + (rh + 5) * i + ')';

Then, for each group, you can add the rectangles, adjusting the horizontal position only (the vertical position was already set in the containing group). Here, you need to bind the inner array elements (the group datum) to each rectangle:

// For each group, create a set of rectangles and them to the inner array
// (the inner array is binded to the group)
    .data(function(d) { return d; })
        .attr('x', function(d, i) { return (rw + 5) * i; })
        .attr('width', rw)
        .attr('height', rh);

I would recomend you to read How Selections Work. Also, I wrote a small jsfidlle with this code:

Related Query