R/axis_scales.R

Defines functions scale_x_dt

Documented in scale_x_dt

#' Date Scale
#'
#' Wrapper for \code{ggplot2::scale_x_date} that generates labels for data variable on x-axis based on input data.
#'
#' @param df data set used for plotting
#' @param x date variable mapped to x-axis
#' @param break_by a character string specifying a time unit to use for axis breaks
#' @param round_unit 	a character string specifying a time unit or a multiple of a unit to be rounded to for the axis breaks.
#' Valid base units are \code{second}, \code{minute}, \code{hour}, \code{day}, \code{week},
#' \code{month}, \code{bimonth}, \code{quarter}, \code{season}, \code{halfyear} and \code{year}.
#' @param labels format to use for displaying labels
#' @param ... additional arguments passed to \code{ggplot2::scale_x_date}
#'
#' @return A \code{ggplot2} date scale object created by
#'   \code{ggplot2::scale_x_date()}.
#'
#' @author Saannidhya Rawat
#' @export
#' @examples
#'
#'
#' library(ggplot2)
#'
#' # use default ggplot2 scale
#' bcat_plt_line(df = economics,
#'               x = date,
#'               y = unemploy,
#'               y_ref = 10000)
#'
#' # use scale_x_dt to break by every 5 years
#' bcat_plt_line(df = economics,
#'               x = date,
#'               y = unemploy,
#'               y_ref = 10000,
#'               x_scale = scale_x_dt(economics, date, round_unit = "5 years"))
scale_x_dt <- function(df,
                       x,
                       break_by = "year",
                       round_unit = "year",
                       labels = scales::date_format("'%y"),
                       ...){

  x_col <- deparse(substitute(x))

  ggplot2::scale_x_date(breaks = lubridate::ceiling_date(seq(from = min(df[[x_col]]),
                                                             to = max(df[[x_col]]),
                                                             by = break_by), unit = round_unit),
                        labels = labels,
                        limits = lubridate::ymd(c(min(df[[x_col]]),
                                                  max(df[[x_col]]))),
                        ...)

}

Try the Rbearcat package in your browser

Any scripts or data that you put into this service are public.

Rbearcat documentation built on March 21, 2026, 5:07 p.m.