1

I need a lot of stacked bar charts in R, so I want to create a very simple function to make it less repetitive.

cntl <- function(.data, varname, xlabname, maintitle){
  print (ggplot(.data) + 
           aes(x=varname, fill=progcat) +
           geom_bar(position="fill") +
           scale_fill_manual(name="Control", values=c("#84c96d", "#cecece", "#000000", "#ffcf5e", "#fa6b37")) +
           xlab(xlabname) + ylab("Proportion of Cohort") +
           labs (title=maintitle) +
           theme(plot.title = element_text(hjust=0.5)))
}

FWIW, progcat has 5 levels. Since I need to mess with the order of the bars, when I call the function like this:

dset %>%
  arrange (progcat) %>%
  mutate(age=factor(age, levels=c("Up to 60", "61+"))) %>%
  cntl (age, dset$age, "Age", "TEST TITLE")

I get the error Error in FUN(X[[i]], ...) : object 'age' not found. If I try to include inherit.aes=FALSE in geom_bar() after the position argument, it then says Error: stat_count() requires an x or y aesthetic. The same code runs fine when hardcoded (without print and .data). I'm relatively new to ggplot; any pointers are super appreciated!

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
MWolcott
  • 23
  • 4

1 Answers1

3

ggplot2’s aes function works with unevaluated arguments. That’s why you can pass column names in a table to it without them being quoted.

To make aes work with variables, you need to tell it to evaluate them. This is easiest using the curly-curly syntax:

cntl <- function(.data, varname, xlabname, maintitle){
  plot(ggplot(.data) + 
           aes(x={{varname}}, fill=progcat) +
           geom_bar(position="fill") +
           scale_fill_manual(name="Control", values=c("#84c96d", "#cecece", "#000000", "#ffcf5e", "#fa6b37")) +
           xlab(xlabname) + ylab("Proportion of Cohort") +
           labs(title=maintitle) +
           theme(plot.title = element_text(hjust=0.5)))
}
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214