Draw grid / click on a specific tick in d3.js

I am trying to create a scatter plot that I was able to do just fine. I would like to split this plot into four quadrants by drawing labels at a specific point on the x axis and a specific point on the y axis. In my case, both axes show percentages, so I would like to draw a line at the 0.50 mark on both axes, but I don't know how to do this and cannot find the documentation that works for me.

This is where 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.

0


source to share


1 answer


The key point here is that you are trying to add two lines that distribute the scatterplot evenly across the four quadrants. To do this, you can find the min / max of your x and y axes (using their respective scales) and then add 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 add these lines to your drawing:



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));

      

This gives you something like this ( see the corresponding full JSFiddle ):

scatterplot axes divided into quadrants

+2


source







All Articles