R/rvn_annual_quantiles_plot.R

Defines functions rvn_annual_quantiles_plot

Documented in rvn_annual_quantiles_plot

#' @title Plot of Annual Median, Upper and Lower Quantiles of Flow
#'
#' @description
#' Creates a plot of the annual flow quantiles provided by the \code{\link{rvn_annual_quantiles}} function.
#'
#' @param qdat Time series object generated by \code{\link{rvn_annual_quantiles}}
#' @param mediancolor Color for the median line
#' @param ribboncolor Color for the lower/upper quantile ribbon
#' @param ribbonalpha Transparency of lower/upper quantile ribbon
#' @param explot Existing ggplot object to which median line and quantile ribbon should be added
#'
#' @return p1 ggplot object of quantiles plot
#' @author Leland Scantlebury, \email{leland@@scantle.com}
#'
#' @examples
#' system.file("extdata","run1_Hydrographs.csv", package="RavenR") %>%
#' rvn_hyd_read(.) %>%
#' rvn_hyd_extract(subs="Sub36",.) ->
#' hyd_data
#'
#' # Calculate quantiles for the simulated hydrograph
#' qdat <- rvn_annual_quantiles(hyd_data$sim)
#' head(qdat)
#'
#' # Plot
#' p <- rvn_annual_quantiles_plot(qdat)
#' p  # view plot
#'
#' # Add a second hydrograph to compare
#' qdat_sim <- rvn_annual_quantiles(hyd_data$sim)
#'
#' p1 <- rvn_annual_quantiles_plot(qdat_sim, mediancolor = 'blue', ribboncolor = 'red', explot = p)
#' p1 # view plot
#'
#' @export rvn_annual_quantiles_plot
#' @importFrom lubridate year date
#' @importFrom ggplot2 ggplot aes geom_point geom_line geom_ribbon xlab ylab scale_x_date
#' @importFrom scales label_date date_format
rvn_annual_quantiles_plot <- function(qdat,
                                      mediancolor='black',
                                      ribboncolor='grey60',
                                      ribbonalpha=0.5,
                                      explot=NULL)
{

  # Export XTS object into df
  dates <- date(qdat)
  qdat <- data.frame(qdat)
  qdat$dates <- dates

  # Rename Columns
  names(qdat) <- c('Lower','Median','Upper','dates')
  Lower <- Median <- Upper <- dates <- NULL # appeasing the R CMD CHECK with ggplot2 conflicts

  if(is.null(explot)) {

    p1 <- ggplot(data=qdat, aes(x = dates)) +
      geom_ribbon(aes(ymin=Lower, ymax=Upper),
                  fill=ribboncolor,
                  alpha=ribbonalpha) +
      geom_line(aes(y=Median),
                color=mediancolor) +
      scale_x_date(labels = date_format("%b")) +
      xlab('Day of Water Year') +
      ylab(expression("Daily Discharge ("*m^3*"/s)")) +
      rvn_theme_RavenR()

  } else {
    # add check that explot is a valid ggplot object
    p1 <- explot +
      geom_ribbon(aes(ymin=Lower, ymax=Upper),
                  fill=ribboncolor, alpha=ribbonalpha) +
      geom_line(aes(y=Median), color=mediancolor)
  }

  return(p1)
}
rchlumsk/RavenR documentation built on April 19, 2024, 5:15 a.m.