Skip to content

Instantly share code, notes, and snippets.

@ptoche
Last active October 17, 2015 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ptoche/435826b42e453369cd6e to your computer and use it in GitHub Desktop.
Save ptoche/435826b42e453369cd6e to your computer and use it in GitHub Desktop.
Convenience function to create 'nice' breaks with ggplot2
## create 'nice' annual breaks for use with ggplot
## because sometimes it's tedious to 'manually' set the minimum and maximum of the date range,
## when the data starts on odd years, like 1927, but you really want the labels to start at 1925
## x denotes the date variable, e.g. x = df$date
## for m = 5, the breaks will be multiples of 5 years
## breaks below min and above max
## replace floor and ceiling with round, if desired
annual_breaks <- function(x, m = 5) {
require('scales')
seq(as.Date(paste0(m*floor(as.numeric(format(min(x), "%Y"))/m), "-01-01")),
as.Date(paste0(m*ceiling(as.numeric(format(max(x), "%Y"))/m), "-01-01")),
by = paste0(m, " years"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment