Thanks to the non-standard evaluation of ggplot, you can't pass in symbol names like that to the ggplot function. The aes
isn't evaluated until you actually print()
the plot. This is why
bb<-bar.plot(df,Fruit,Bug)
doesn't give the same error. But at that point the variable j
that lived inside the function doesn't exist any more. If you want to dynamically specify columns of data to use as values in an aes()
expression, you should use aes_string
. And if you want to be able to pass in symbol names rather than strings, you can convert them to characters using substitute
. For example, this will work
bar.plot <- function(dat,j,c){
ggplot(dat, aes_string(x=substitute(j)), aes(y=..count..)) +
geom_bar(aes_string(fill = substitute(c)), position = "dodge")
}
bar.plot(df,Fruit,Bug)