R/ggfunc.R

Defines functions ggfunc

Documented in ggfunc

#' plot a function
#'
#
#' @param func The name of a function
#' @param x a numeric vector to pass to the function
#' @param from the lower limit of the x-axis
#' @param to the upper limit of the x-axis
#' @param n the number of x values to be evaluated
#' @param xname character; argument of the function in func, the name of the x axis
#' @param xlab label of the x-axis
#' @param ylab label of the y-axis
#' @param xlim restrict the range of the function
#' @param args list of the additional argument of the function
#' @param color the color of the line. defaults to "red"
#' @param size the size of the line. defaults to 1.15
#' @param ... Additional arguments to stat_function()
#' @examples
#' ggfunc(dnorm(x), from = -15, to = 15)
#' @export
ggfunc <- function(func, x, from = NULL, to = NULL, n = 200,
                   xname = "\u03C7", xlab = xname, ylab = NULL,
                   xlim = NULL, args = list(), color = "red", size = 1.15, ...) {
  sexpr <- substitute(func)
  if (is.function(func)) {
    funky_function <- func
  } else {
    stop("please provide a function")
  }
  if (is.null(ylab)) ylab <- paste0("\u0192 ", "( ", "\u03C7", " )")

  if (is.null(x) == FALSE) {
    tibble(x = x) %>%
      ggplot(aes(x = x)) +
      stat_function(
        fun = funky_function,
        n = n,
        xlim = xlim,
        args = args,
        color = color,
        size = size,
        ...
      ) +
      labs(
        x = xlab,
        y = ylab
      )
  } else {
    tibble(x = c(from, to)) %>%
      ggplot(aes(x = x)) +
      stat_function(
        fun = funky_function,
        n = n,
        xlim = xlim,
        args = args,
        color = color,
        size = size,
        ...
      ) +
      labs(
        x = xlab,
        y = ylab
      )
  }
}
abnormally-distributed/abdisttools documentation built on May 5, 2019, 7:07 a.m.