d3.js

Customize the d3 month or year tick format


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

d3.axisBottom(x)

which output the following graph:

months and years

How can I manually create and customize this format? In particular, I'd like to use short month names, like "Oct", so that "October" doesn't obscure the following year label.


Solution

  • Use tickFormat to format the ticks in your x axis. In your case, .tickFormat(d3.timeFormat("%b")) will return short month names (but it will make the year disappear).

    Here is 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, 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 keep the month / year default functionality, you need to create your own custom 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 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>