Skip to content

Instantly share code, notes, and snippets.

@noblemillie
Last active July 11, 2018 03:34
Show Gist options
  • Save noblemillie/3b002cfa0f0fd44a6d30b07452cadeb6 to your computer and use it in GitHub Desktop.
Save noblemillie/3b002cfa0f0fd44a6d30b07452cadeb6 to your computer and use it in GitHub Desktop.
basic grid and axes
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body {
margin:0;
position:fixed;
top:0;
right:0;
bottom:0;
left:0; }
.axis .grid-line{
stroke: black;
shape-rendering: crispEdges;
stroke-opacity: .1;
}
</style>
</head>
<body>
<script type="text/javascript">
var height = 500,
width = 500,
margin = 25;
var svg = d3.select("body").append("svg")
.attr("class", "axis")
.attr("width", width)
.attr("height", height);
function renderXAxis(){
var axisLength = width - 2 * margin;
var scale = d3.scaleLinear()
.domain([0, 100])
.range([0, axisLength]);
var xAxis = d3.axisBottom()
.scale(scale);
svg.append("g")
.attr("class", "x-axis")
.attr("transform", function(){
return "translate(" + margin + "," + (height - margin) + ")";
})
.call(xAxis);
d3.selectAll("g.x-axis g.tick")
.append("line")
.classed("grid-line", true)
.attr("x1", 0)
.attr("y1", 0)
.attr("x2", 0)
.attr("y2", - (height - 2 * margin));
}
function renderYAxis(){
var axisLength = height - 2 * margin;
var scale = d3.scaleLinear()
.domain([100, 0])
.range([0, axisLength]);
var yAxis = d3.axisLeft()
.scale(scale);
svg.append("g")
.attr("class", "y-axis")
.attr("transform", function(){
return "translate(" + margin + "," + margin +")";
})
.call(yAxis);
d3.selectAll("g.y-axis g.tick")
.append("line")
.classed("grid-line", true)
.attr("x1", 0)
.attr("y1", 0)
.attr("x2", axisLength)
.attr("y2", 0);
}
renderYAxis();
renderXAxis();
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment