Skip to content

Commit

Permalink
Add function time_axis()
Browse files Browse the repository at this point in the history
  • Loading branch information
kbroman committed May 4, 2024
1 parent 7ed55a0 commit c97929a
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 3 deletions.
4 changes: 2 additions & 2 deletions DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Package: broman
Version: 0.81-1
Date: 2024-02-05
Version: 0.81-2
Date: 2024-05-03
Title: Karl Broman's R Code
Description: Miscellaneous R functions, including functions related to
graphics (mostly for base graphics), permutation tests, running
Expand Down
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export(strwidth2lines)
export(strwidth2xlim)
export(switchv)
export(theme_karl)
export(time_axis)
export(trap)
export(triarrow)
export(trigrid)
Expand Down
4 changes: 3 additions & 1 deletion NEWS.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
Revision history for the R/broman package
-----------------------------------------

## Version 0.81-1, 2024-02-05
## Version 0.81-2, 2024-05-03

- Small change to documentation for `objectsizes()` (Mb -> MB)

- Added function `time_axis()` for helping set up axis labels for date/times.


## Version 0.80, 2022-07-08

Expand Down
40 changes: 40 additions & 0 deletions R/time_axis.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#' Set up a time-based axis
#'
#' Set up a time-based axis for base graphics
#'
#' @param times A vector of date/times that will be plotted
#'
#' @param n Number of values to use in axis
#'
#' @return A data frame with the numeric values to plot plus labels to use.
#'
#' @export

time_axis <-
function(times, n=8)
{
if(!("POSIXct" %in% class(times) || "POSIXt" %in% class(times))) {
stop("times should be a vector of date/times")
}

prettyx <- pretty(times, n=n)

r <- range(as.numeric(times))
dr <- diff(r)
# determine range
if(dr < 70) { # seconds
labels <- format(prettyx, format="%S")
}
else if(dr < 60*70) { # minutes
labels <- format(prettyx, format="%H:%M")
}
else if(dr < 60*60*26) { # hours
labels <- format(prettyx, format="%H:%M")
}
else { # days
labels <- format(prettyx, format="%Y-%m-%d")
}

# return vector of "pretty" times + labels
data.frame(x=prettyx, label=labels)
}
19 changes: 19 additions & 0 deletions man/time_axis.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit c97929a

Please sign in to comment.