How can I generate tick for each year in D3?
The following code seems to work when my data spans across several years, but it displays months when there are only few years in data (say 3 years)?
var xAxisScale = d3.scaleTime()
.domain([new Date(min, 0, 1, 0), new Date(max, 0, 1, 0)])
.rangeRound([100,width])
xAxisScale.ticks(d3.timeYear.every(1));
You can set the tick format explicitly using tickFormat
in your axis generator::
xAxis.tickFormat(d3.timeFormat("%Y"));
Check the snippet, the first axis goes from 2000 to 2016, the second one from 2014 to 2016. The third is the same, but with ticks(d3.timeYear)
to keep only 1 tick per year:
var width = 400, height = 200;
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
var xAxisScale1 = d3.scaleTime()
.domain([new Date(2000, 0, 1), new Date(2016, 0, 1)])
.rangeRound([20,width - 20]);
var xAxisScale2 = d3.scaleTime()
.domain([new Date(2014, 0, 1), new Date(2016, 0, 1, 0)])
.rangeRound([20,width - 20]);
var xAxis1 = d3.axisBottom(xAxisScale1);
var xAxis2 = d3.axisBottom(xAxisScale2).tickFormat(d3.timeFormat("%Y"));
svg.append("g").call(xAxis1);
svg.append("g").attr("transform", "translate(0,40)").call(xAxis2);
svg.append("g").attr("transform", "translate(0,80)").call(xAxis2.ticks(d3.timeYear));
<script src="https://d3js.org/d3.v4.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With