I'm trying to create a scatterplot, which I've been able to do just fine. I'd like to separate this plot into four quadrants by drawing ticklines at a specific point on the x axis and specific point on the y axis. In my case, both axes are showing percentages, so I'd like to draw a line at the tick for 0.50 on both axes, but I haven't any clue how to do this and can't find any documentation that is working for me.
Here's what I have to define my axes:
var xAxis = d3.svg.axis()
.scale(x)
.ticks(20)
.tickSubdivide(true)
.tickSize(6, 3, 0)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.ticks(20)
.tickSubdivide(true)
.tickSize(6, 3, 0)
.orient("left");
Any insight would be appreciated.
解决方案
The key point here is you're trying to append two lines that divide the scatterplot evenly into four quadrants. To do that, you can find the min/max of your x- and y-axes (using their corresponding scales), and then append lines at the midpoint:
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}]
Then you just need to append these lines to your figure:
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", "#000")
.style("stroke-dasharray", (10, 10));
Doing so gives you something like this (see corresponding complete JSFiddle):