Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3.js default axis.tickFormat to 24 hour clock

Tags:

d3.js

I really like the default behavior of axis.tickFormat when plotting things over time, and just creating my x axis like this:

var xAxisBottom = d3.svg.axis().scale(xScale);

I'm using the brush function, so that the user can scale along the x-axis, and so it's values has to update accordingly. If the user looks at data over a whole year, ticks with months is good. If the user looks at data over a day, ticks with hours and minutes is good. And so on.

The good thing is that the default behavior of the axis is like this. The bad thing is that it shows the hours in AM/PM, and I would like to change that to a 24 hour clock.

I know I can set my own tickFormat based on the current span of the brush, but in that case I don't know how to get something like the picture below, where different formats are mixed.

enter image description here

So, is there an easy way to get 24 hour clock instead of AM/PM?

like image 459
Joel Avatar asked Mar 27 '13 07:03

Joel


2 Answers

Not easy as in "call a single line of code", but you can roll your own time format easy enough. See here for an example. The key idea is that you have a list of date formats and a filter function which, given a date, returns true if the associated format is to be used. In your case you would need only two levels, one to display the date (if the date is midnight) or the time (if the date is 12 noon).

like image 183
Lars Kotthoff Avatar answered Jan 04 '23 16:01

Lars Kotthoff


It's worth noting that if you're using UTC time on your axis instead of local time, then d3 calls a different set of formatters internally. You need this:

          return (d3.utcSecond(date) < date ? formatMillisecond
          : d3.utcMinute(date) < date ? formatSecond
          : d3.utcHour(date) < date ? formatMinute
          : d3.utcDay(date) < date ? formatHour
          : d3.utcMonth(date) < date ? (d3.utcWeek(date) < date ? formatDay : formatWeek)
          : d3.utcYear(date) < date ? formatMonth
          : formatYear)(date);

instead of the calls referenced in the linked example above. The change is to substitute "d3.utcXXX(date)" for "d3.timeXXX(date)."

like image 42
Mark Faust Avatar answered Jan 04 '23 15:01

Mark Faust