user3562812
user3562812

Reputation: 1839

How do I generate axis tick for every year in D3?

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));

Upvotes: 5

Views: 8563

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102219

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>

Upvotes: 6

Related Questions