user6506263
user6506263

Reputation:

d3 - how to format date on x-axis

Super new to d3, and I apologize if this question is poorly worded.

I'm attempting to alter pre-existing code and reformat the dates that appear on the x-axis of my chart. Currently, my x-axis is showing a tick for each month, and the month is not abbreviated, e.g. January, February, etc.

For space-constraint reasons, I need to abbreviate these months, e.g. Jan, Feb, etc.

This is the code that creates the x-axis:

   master.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(d3axis.axisBottom()
        .scale(x));

I believe that I need to chain a function to the axisBottom call. I have been looking at tickFormat and timeFormat in the docs, and also at this example. I'm trying to do something like:

    master.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(d3axis.axisBottom()
        .tickFormat(d3axis.timeFormat("%m"))
        .scale(x));

but I get this error: npmD3Axis.default.timeFormat is not a function

Can anyone point me in the right direction? Thanks!

Upvotes: 5

Views: 11602

Answers (1)

Chandu
Chandu

Reputation: 2129

axis.ticks(d3.time.months, 1).tickFormat(d3.time.format("%b"));

You have to change the formate form %m to %b

for d3.js v4

axis.ticks(d3.timeMonth, 1).tickFormat(d3.timeFormat('%b'));

Upvotes: 7

Related Questions