Reduce months on the x axis

How can I shorten the month mark from October to October.

When the default chart shows October, it should display October, and the years should be saved.

I think I should use

.tickFormat(d3.timeFormat("%b")) 

but when I use it, years are not displayed.

How can I apply tickFormat only if the legend displays the month?

+5
source share
1 answer

The problem with these settings is that axes are automatically generated in D3, and setting some things, such as the exact number of ticks, can be a difficult task. The situation is even more complicated on a time scale, which makes your business worse: on a time scale, it is difficult to know in advance how ticks will be formatted.

As you already know, converting all ticks to the abbreviation of the month is easy. However, if you want to keep the default structure and only change ticks with months, you will have to change the axis after it has been created. In this example, use each .

So, first create the default axis. Here he is:

 var svg = d3.select("svg"); var scale = d3.scaleTime() .range([20, 480]) .domain([new Date("06-01-2016"), new Date("06-01-2017")]); var axis = d3.axisBottom(scale) .ticks(4); var gX = svg.append("g") .attr("transform", "translate(0,50)") .call(axis); 
 <script src="https://d3js.org/d3.v4.min.js"></script> <svg width="500" height="100"></svg> 

As you can see, we have four ticks: three ticks with full months and one tick with a year.

Now let's check the format of each tick with this and compare it with the database ( d ), converting the text to the abbreviated name of the month, only if it is already a month:

 gX.selectAll(".tick").each(function(d) { if (this.textContent === d3.timeFormat("%B")(d)) { d3.select(this).select("text").text(d3.timeFormat("%b")(d)) } }) 

Here is the result:

 var svg = d3.select("svg"); var scale = d3.scaleTime() .range([20, 480]) .domain([new Date("06-01-2016"), new Date("06-01-2017")]); var axis = d3.axisBottom(scale) .ticks(4); var gX = svg.append("g") .attr("transform", "translate(0,50)") .call(axis); gX.selectAll(".tick").each(function(d) { if (this.textContent === d3.timeFormat("%B")(d)) { d3.select(this).select("text").text(d3.timeFormat("%b")(d)) } }) 
 <script src="https://d3js.org/d3.v4.min.js"></script> <svg width="500" height="100"></svg> 
+3
source

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


All Articles