Skip to content

Instantly share code, notes, and snippets.

@mbostock
Forked from mbostock/.block
Last active April 16, 2017 02:59
Show Gist options
  • Save mbostock/6186172 to your computer and use it in GitHub Desktop.
Save mbostock/6186172 to your computer and use it in GitHub Desktop.
Left-Aligned Ticks
license: gpl-3.0

This example demonstrates how to create left-aligned axis labels using post-selection. First, the scale’s domain and range are extended by one month on either end to create additional space for the first and last tick. Then, after the axis is rendered, the text label elements are selected, and then attributes on the elements are modified to customize the label appearance.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.axis text {
font: 10px sans-serif;
}
.axis line,
.axis path {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var margin = {top: 250, right: 40, bottom: 250, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var t1 = new Date(2012, 0, 1),
t2 = new Date(2013, 0, 1),
t0 = d3.time.month.offset(t1, -1),
t3 = d3.time.month.offset(t2, +1);
var x = d3.time.scale()
.domain([t0, t3])
.range([t0, t3].map(d3.time.scale()
.domain([t1, t2])
.range([0, width])));
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var svg = d3.select("body").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 + ")");
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.attr("y", 6)
.attr("x", 6)
.style("text-anchor", "start");
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment