d3:grid-lines

by Richard Hunter

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.5/d3.min.js"></script>
<p>based on answer at <a href="https://stackoverflow.com/questions/15580300/proper-way-to-draw-gridlines">Stack Overflow</a></p>

CSS

svg {
  background: #fff1e5;
}

JavaScript

const margins = {
  top: 10,
  bottom: 50,
  left: 20,
  right: 20,
};

const width = 700;
const height = 400;
const ticks = 25;

const svg = renderSVG(width, height);

const xScale = d3.scaleLinear()
  .domain([0, 10])
  .range([margins.left, width - margins.right])

const yScale = d3.scaleLinear()
  .domain([0, 10])
  .range([height - margins.bottom, margins.top])

svg.append('g').selectAll('line').data(xScale.ticks(ticks)).enter().append('line')
  .attr('x1', d => xScale(d))
  .attr('y1', margins.top)
  .attr('y2', height - margins.bottom)
  .attr('x2', d => xScale(d))
  .attr('stroke', 'blue')
  .attr('shape-rendering', 'crispEdges')

svg.append('g').selectAll('line').data(yScale.ticks(ticks)).enter().append('line')
  .attr('x1', margins.left)
  .attr('x2', width - margins.right)
  .attr('y1', d => yScale(d))
  .attr('y2', d => yScale(d))
  .attr('stroke', 'red')
  .attr('shape-rendering', 'crispEdges')

function renderSVG(width, height) {
  return d3.select('body')
    .append('svg')
    .attr('width', width)
    .attr('height', height);
}