R/plot_main_effects.R

#' @title Plot Main Effects
#' @description Create a ggplot for a singluar input & output parameter
#' @param df A wide-tibble containing data for each input parameter
#' @param ip Input-Parameter: a vector of strings containing the column names that are designated as input parameters by the user
#' @param op Output-Parameter: a single string designating the column name of the output parameter which should be numeric
#' @param units A string contaning particular units for respective input parameter. Latex2exp can be used in the string to specify math notation for units.
#' @param scale_max_min An integer vector containing the scale value for the plot.
#' @return A plot object showing the Main Effect Plot for a single input & output parameter.
#' @importFrom tidyr gather
#' @importFrom dplyr %>% group_by summarise pull
#' @importFrom latex2exp TeX
#' @import ggplot2
plot_main_effects <- function(df, ip, op, units, scale_max_min) {
  # Turn strings into objects
  input_p <- sym(ip)
  output_p <- sym(op)

  # Generate sequence of values for y-axis scales
  break_scale <- seq(scale_max_min[1], scale_max_min[2], diff(scale_max_min)/5)

  # Use output_parameter vector to compute mean (dashed line)
  output_dat <- df %>% pull(!!output_p)

  # Main plotting block
  ggplot(data = df, aes(x = !!input_p, y = !!output_p, group = 1)) +
    stat_summary(fun.y = mean, geom = "point") +
    stat_summary(fun.y = mean, geom = "line") +
    geom_hline(aes(yintercept = mean(output_dat)), linetype = "dashed") +
    scale_y_continuous(breaks = break_scale) +
    coord_cartesian(ylim = c(scale_max_min[1], scale_max_min[2])) +
    labs(title = tools::toTitleCase(gsub("_", " ", ip)),
         x = TeX(units)) +
    theme_bw() +
    theme(axis.title.y = element_blank(),
          plot.title = element_text(hjust = .5, size = 15),
          text = element_text(size = 15))
}
dylanjm/meplotR documentation built on May 9, 2019, 1:08 a.m.