How can I generate an axis checkmark for each year in D3?

How can I generate a tick for each year in D3?

The following code seems to work when my data spans several years, but months are displayed when there is only a few years in the 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));
+4
source share
1 answer

You can set the tick format explicitly using the tickFormataxis in your generator ::

xAxis.tickFormat(d3.timeFormat("%Y"));

Check the fragment, the first axis goes from 2000 to 2016, the second - from 2014 to 2016. The third is the same, but with ticks(d3.timeYear)to save 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>
Run codeHide result
+5
source

Source: https://habr.com/ru/post/1655546/


All Articles