A better approach than your current solution would be to use scale.ticks() explicitly to get the tick values. The advantage of this is that it will still work if for some reason you change the number of ticks.
To get an alternative grid pattern instead of a single fill, you can use something like this code.
.attr("fill", function(d, i) { return (i % 2) == 1 ? "green" : "blue"; })
Finally, to get the full grid pattern, you can use an explicit loop, as you suggested, or nested options . The idea here is to first go through the y ticks, create g for each element, and then pass x tags for each of these groups. In code, it looks something like this.
svg.selectAll("g.grid") .data(y.ticks()).enter().append("g").attr("class", "grid") .selectAll("rect") .data(x.ticks()).enter().append("rect");
To set a position, you can access the indexes in the upper and lower level data arrays like this.
.attr("x", function(d, i) { return xScale(i); }) .attr("y", function(d, i, j) { return yScale(j); })
To set the position of x , you need the index of the internal array (passed to the set of elements g ), which can be accessed through the second argument of your callback. For an external array, just add one more argument ( j here).
And thatโs really all. Fill out jsfiddle here . To dynamically update this grid, you just have to enter new check values โโ(obtained from scale.ticks() ), match the existing data and handle the input / update / output selection in the usual way.
If you want to do without auxiliary scales (i.e. without .rangeBand() ), you can calculate the width / height of the rectangles using the scale of the scale and dividing it by the number of ticks minus 1. In general, this makes the code a little ugly (mainly because that you need less rectangle than ticks, and therefore you need to subtract / delete it), but a little more general. The jsfiddle that uses this approach is here .