Set month format d3 or year

So, I made a chart in d3 and used the default x-axis format,

d3.axisBottom(x) 

which display the following graph:

months and years

How can I manually create and configure this format? In particular, I would like to use short monthly names such as “October”, so “October” does not hide the label for next year.

+6
source share
1 answer

Use tickFormat to format ticks along the x axis. In your case .tickFormat(d3.timeFormat("%b")) will return the short month names (but this will cause the year to disappear).

Here is a demo:

 var svg = d3.select("body") .append("svg") .attr("width", 500) .attr("height", 100) var xScale = d3.scaleTime() .domain([new Date("2014-01-01"), new Date("2016-01-01")]) .range([0, 450]); var xAxis = d3.axisBottom(xScale) .tickFormat(d3.timeFormat("%b")); svg.append("g") .call(xAxis); 
 <script src="https://d3js.org/d3.v4.min.js"></script> 

To preserve the default functionality of the month / year, you need to create your own format.

 var xAxis = d3.axisBottom(xScale) .tickFormat(function(date){ if (d3.timeYear(date) < date) { return d3.timeFormat('%b')(date); } else { return d3.timeFormat('%Y')(date); } }); 

Check out the demo:

 var svg = d3.select("body") .append("svg") .attr("width", 500) .attr("height", 100) var xScale = d3.scaleTime() .domain([new Date("2014-01-01"), new Date("2016-01-01")]) .range([0, 500]); var xAxis = d3.axisBottom(xScale) .tickFormat(function(date){ if (d3.timeYear(date) < date) { return d3.timeFormat('%b')(date); } else { return d3.timeFormat('%Y')(date); } }); svg.append("g") .attr("class", "x axis") .call(xAxis); d3.selectAll(".ticks"); 
 <script src="https://d3js.org/d3.v4.min.js"></script> 
+11
source

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


All Articles