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>
source share