write a function to produce a plot in R

28 Views Asked by At

I am trying to write a function that builds a plot, but as a return I get an empty plot. Can you advice what can I be doing so wrong? Clearly something is wrong with aes portion, but cannot figure out what exactly is going wrong there. Thank you!

data <- data.frame(
  PAYER = c("A","B","A","B","A","B","A","A","B","A","A","B","A","B","A","A","B","A","B","B","A"),
  PERIOD = c("POST","PRE","POST","PRE","PRE","PRE","POST","PRE","POST","PRE","POST","PRE","POST","PRE","PRE","PRE","POST","PRE","PRE","POST","POST"),
  VALUE = c(100,100,200,250,500,150,400,500,350,200,500,350,200,500,350,200,250,500,150,400,500),
  COHORT = c(1,0,0,0,1,1,0,1,1,0,1,1,0,0,0,1,1,0,1,1,0))


plot_density <- function(df, colx, payer){
  subset <- df %>%
    dplyr::filter(PAYER == payer) %>%
    as.data.frame()
  
  vector <- subset %>%
    dplyr::select(colx) %>% 
    pull()
  
  var_breaks <- pretty(range(vector),
                       n = nclass.Sturges(vector),
                       min.n = 1)
  plot <- 
    ggplot(subset, aes(x = colx)) + 
    geom_density(lwd = 1, color = "black",
                 fill = "yellow", alpha = 0.7) +
    scale_x_discrete(breaks = var_breaks)+
    facet_grid(cols = vars(factor(PERIOD, levels = c("PRE","POST"))), rows = vars(COHORT)) +
    labs(title = "",
         x = "",
         y = "Density") 
  
  return(plot) 
}
plot_density(data,"VALUE","A") # returns empty graph

plot_density(data,VALUE,"A") # errors out, saying that VALUE does not exist, but it does!

enter image description here

I tried the plot code without building function and they work fine

0

There are 0 best solutions below