Skip to content

Instantly share code, notes, and snippets.

@wadefagen
Last active March 31, 2021 15:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wadefagen/ce5d308d8080130de10f21254273e30c to your computer and use it in GitHub Desktop.
Save wadefagen/ce5d308d8080130de10f21254273e30c to your computer and use it in GitHub Desktop.
Simple gridlines in d3.js (v4+)
<!DOCTYPE html>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<div id="chart"></div>
<style>
.grid line {
stroke: #ddd;
}
</style>
<script>
// Sample data
var data = [87, 34, 45, 67, 21, 94, 18];
// Boilerplate
var margin = { top: 50, right: 50, bottom: 50, left: 50 },
width = 800 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
var svg = d3.select("#chart")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Scale
var scale = d3.scaleLinear()
.domain( [0, 100] )
.range( [0, width] );
// Axis
var axis = d3.axisTop()
.scale(scale);
svg.append("g")
.call(axis);
// Gridline
var gridlines = d3.axisTop()
.tickFormat("")
.tickSize(-height)
.scale(scale);
svg.append("g")
.attr("class", "grid")
.call(gridlines);
// Visual Encodings
svg.selectAll("circles")
.data(data)
.enter()
.append("circle")
.attr("cx", function (d) { return scale(d); })
.attr("cy", 100)
.attr("r", 5)
.attr("fill", "blue");
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment