R/bcat_plt_line.R

Defines functions bcat_plt_line

Documented in bcat_plt_line

#' Line plot utility
#'
#' Create a line plot using ggplot2 graphics. This function is a wrapper to create
#' commonly used styles of line plots. Additional layers can be added to this plot
#' as needed. More complicated plots can be creating using individual ggplot2 layers.
#'
#' @param df The data to be displayed
#' @param x Variable to map to the x-axis
#' @param y Variable to map to the y-axis
#' @param color Variable to map to the color aesthetic
#' @param linetype Variable to map to the linetype aesthetic
#' @param facet Facetting variable(s). Note: must wrap in \code{vars()}, e.g, \code{facet = vars(var1, var2)}
#' @param x_lab Label for x-axis
#' @param y_lab Label for y-axis
#' @param title Plot title
#' @param subtitle Plot subtitle
#' @param caption Plot caption
#' @param legend_lab Legend title
#' @param legend_position legend position. "bottom" or "right"
#' @param legend_hide Set to \code{TRUE} to hide the legend
#' @param x_scale \code{scale_x_} function to apply to x-axis.
#' @param y_scale \code{scale_y_} function to apply to y-axis.
#' @param color_scale \code{scale_color_} function to apply to colors.
#' @param facet_scale Shoud facet scales be fixed ("fixed", the default), free ("free"),
#'                    or free in one dimension ("free_x", "free_y")?
#' @param nrow Number of facet rows
#' @param ncol Number of facet columns
#' @param layer_points Set to \code{TRUE} to plot points
#' @param x_refline Vector of x-values at which to draw vertical reference lines
#' @param y_refline Vector of y-values at which to draw horizontal reference lines
#' @param x_highlight_min Vector of min x-values at which to start draw rectangle annotation
#' @param x_highlight_max Vector of max x-values at which to end rectangle annotation
#' @param y_highlight_min Vector of min y-values at which to start draw rectangle annotation
#' @param y_highlight_max Vector of max y-values at which to end rectangle annotation
#' @param y_ribbon_min Variable to use as minimum values for ribbon around y at each value of x
#' @param y_ribbon_max Variable to use as maximum values for ribbon around y at each value of x
#' @param y_error_min Variable to use as minimum values for error bars around y at each value of x
#' @param y_error_max Variable to use as maximum values for error bars around y at each value of x
#' @param y_error_width Width of error bars
#' @return A \code{ggplot2} plot object.
#' @author Saannidhya Rawat
#' @family plots
#' @export
#'
#' @examples
#' library(ggplot2)
#' library(scales)
#'
#' # basic time series plot with a reference line
#' bcat_plt_line(df = economics,
#'               x = date,
#'               y = unemploy,
#'               y_scale = scale_y_continuous(labels = comma_format()),
#'               y_refline = 10000)
#'
#' # line plot with facets and highlight periods
#' bcat_plt_line(df = economics_long,
#'              x = date,
#'              y = value,
#'              color = variable,
#'              facet = vars(variable),
#'              x_lab = "Decade",
#'              y_lab = "Value",
#'              legend_lab = NULL,
#'              facet_scale = "free_y",
#'              x_highlight_min = as.Date(c("2000-01-01", "2008-01-01")),
#'              x_highlight_max = as.Date(c("2002-01-01", "2010-01-01")),
#'              ncol = 1)
#'
bcat_plt_line <- function(df,
                          x,
                          y,
                          color = NULL,
                          linetype = NULL,
                          facet = NULL,
                          x_lab = ggplot2::waiver(),
                          y_lab = ggplot2::waiver(),
                          title = ggplot2::waiver(),
                          subtitle = ggplot2::waiver(),
                          caption = ggplot2::waiver(),
                          legend_lab = ggplot2::waiver(),
                          legend_position = "bottom",
                          legend_hide = FALSE,
                          x_scale = NULL,
                          y_scale = NULL,
                          color_scale = Rbearcat::scale_colour_UC(),
                          facet_scale = c("fixed", "free_y", "free_x", "free"),
                          nrow = NULL,
                          ncol = NULL,
                          layer_points = FALSE,
                          x_refline = NULL,
                          y_refline = NULL,
                          x_highlight_min = NULL,
                          x_highlight_max = NULL,
                          y_highlight_min = NULL,
                          y_highlight_max = NULL,
                          y_ribbon_min = NULL,
                          y_ribbon_max = NULL,
                          y_error_min = NULL,
                          y_error_max = NULL,
                          y_error_width = 1){

  # validation --------------------------------------------------------------

  .validate_df(df)

  # prelims -----------------------------------------------------------------

  facet_scale <- match.arg(facet_scale)

  # quoting arg to check if variable exists in data later
  y_rib_min <- deparse(substitute(y_ribbon_min))
  y_rib_max <- deparse(substitute(y_ribbon_max))
  y_err_min <- deparse(substitute(y_error_min))
  y_err_max <- deparse(substitute(y_error_max))

  # plot-base ---------------------------------------------------------------

  p <- ggplot2::ggplot(data = df,
                       mapping = ggplot2::aes(x = {{x}},
                                              y = {{y}},
                                              color = {{color}},
                                              linetype = {{linetype}}))

  # ribbon-layer ------------------------------------------------------------

  if(!is.null(df[[y_rib_min]]) & !is.null(df[[y_rib_max]])){

    p <- p + ggplot2::geom_ribbon(mapping = ggplot2::aes(ymin = {{y_ribbon_min}},
                                                         ymax = {{y_ribbon_max}}),
                                  color = .uc_reference_color(0.5))

  }

  # line-layer-and-scales ---------------------------------------------------

  p <- p + ggplot2::geom_line() +
    # scale options
    x_scale +
    y_scale +
    color_scale

  # facets ------------------------------------------------------------------

  if(!is.null(facet)){

    p <- p + ggplot2::facet_wrap(facets = facet,
                                 nrow = nrow,
                                 ncol = ncol,
                                 scales = facet_scale)

  }

  # labels ------------------------------------------------------------------

  p <- p + ggplot2::labs(x = x_lab,
                         y = y_lab,
                         title = title,
                         subtitle = subtitle,
                         caption = caption,
                         color = legend_lab,
                         linetype = legend_lab)

  # layer-points ------------------------------------------------------------

  if(layer_points){

    p <- p + ggplot2::geom_point()

  }

  # reference-lines ---------------------------------------------------------

  if(!is.null(x_refline)){

    p <- p + ggplot2::geom_vline(xintercept = x_refline)

  }

  if(!is.null(y_refline)){

    p <- p + ggplot2::geom_hline(yintercept = y_refline)

  }

  # highlight-regions -------------------------------------------------------

  # if all provided, map all to args
  if(!is.null(x_highlight_min) &
     !is.null(x_highlight_max) &
     !is.null(y_highlight_min) &
     !is.null(y_highlight_max)){

    p <- p + ggplot2::annotate("rect",
                               xmin = x_highlight_min,
                               xmax = x_highlight_max,
                               ymin = y_highlight_min,
                               ymax = y_highlight_max,
                               alpha = 0.40,
                               fill = .uc_highlight_fill()
    )

  }

  # if only x-region provided, extend y-min and max to full range
  if(!is.null(x_highlight_min) &
     !is.null(x_highlight_max) &
     is.null(y_highlight_min) &
     is.null(y_highlight_max)){

    p <- p + ggplot2::annotate("rect",
                               xmin = x_highlight_min,
                               xmax = x_highlight_max,
                               ymin = -Inf,
                               ymax = Inf,
                               alpha = 0.40,
                               fill = .uc_highlight_fill()
    )

  }

  # if only y-region provided, extend x-min and max to full range
  if(is.null(x_highlight_min) &
     is.null(x_highlight_max) &
     !is.null(y_highlight_min) &
     !is.null(y_highlight_max)){

    p <- p + ggplot2::annotate("rect",
                               ymin = y_highlight_min,
                               ymax = y_highlight_max,
                               xmin = -Inf,
                               xmax = Inf,
                               alpha = 0.40,
                               fill = .uc_highlight_fill()
    )

  }

  # error-bar-layer ---------------------------------------------------------

  if(!is.null(df[[y_err_min]]) & !is.null(df[[y_err_max]])){

    p <- p + ggplot2::geom_errorbar(mapping = ggplot2::aes(ymin = {{y_error_min}},
                                                           ymax = {{y_error_max}}),
                                    width = y_error_width)

  }


  # add-theme-and-print -----------------------------------------------------

  p + Rbearcat::theme_UC(legend_position = legend_position,
                        legend_hide = legend_hide)

}

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.