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!