Draw gridline/tickline at a specific tick in d3.js

http://stackoverflow.com/questions/27065609/draw-gridline-tickline-at-a-specific-tick-in-d3-js

by Max Leiserson

HTML

<script src="http://d3js.org/d3.v3.min.js"></script>

CSS

.axis text {
  font: 10px sans-serif;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

JavaScript

// Set up the SVG, with a margin along the left/right, top/bottom
var svg = d3.select("body")
    .append("svg")
    .attr("width", 350)
    .attr("height", 330),
    fig = svg.append("g").attr("transform", "translate(40, 20)");

// Create two 1-to-1 scales
var x = d3.scale.identity().domain([0,300]);
var y = d3.scale.identity().domain([0,300]);

// Add the axes
var xAxis = d3.svg.axis()
    .scale(x)
    .orient("top");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

fig.append("g").attr("class", "axis").call(xAxis);
fig.append("g").attr("class", "axis").call(yAxis);

// Add the lines at 0.5
var startX = d3.min(x.domain()),
    endX = d3.max(x.domain()),
    startY = d3.min(y.domain()),
    endY = d3.max(y.domain());
var lines = [{x1: startX, x2: endX, y1: (startY + endY)/2, y2: (startY + endY)/2},
             {x1: (startX + endX)/2, x2: (startX + endX)/2, y1: startY, y2: endY}]
fig.selectAll(".grid-line")
    .data(lines).enter()
    .append("line")
    .attr("x1", function(d){ return x(d.x1); })
    .attr("x2", function(d){ return x(d.x2); })
    .attr("y1", function(d){ return y(d.y1); })
    .attr("y2", function(d){ return y(d.y2); })
    .style("stroke", "#666666")
    .style("stroke-dasharray", (10, 10));