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.
So, is there an easy way to get 24 hour clock instead of AM/PM?
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).
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)."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With