How to change the tick value in d3, javascript from "1900" to "January"?

Viewed 68

When I tried to use scaleTime from d3 to create an y-axis, I found that the tick that should be the first month, "January" actually shows the name of that specific year. How can I get it to show the name of the month instead of the year?

Here are my code for generating the y-axis.

var yScale = d3.scaleTime().domain([new Date(0, -1, 10), new Date(0, 12)]).range([0, 600]);
var yAxis = d3.axisLeft(yScale).ticks(14);
g.append("g").call(yAxis);

Here is what displays on the screen. enter image description here

1 Answers

Use tickFormat:

const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

const yScale = d3.scaleTime().domain([new Date(0, -1, 10), new Date(0, 12)]).range([0, 600]);
const yAxis = d3
  .axisLeft(yScale)
  .ticks(14)
  .tickFormat(d => monthNames[d.getMonth()])
d3.select('svg').append("g")
  .attr('transform', 'translate(100, 20)')
  .call(yAxis);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width="200" height="1000"/>

Related