2

For some reason when I do the following:

Fruit <- c(rep("Apple",3),rep("Orange",5))
Bug <- c("worm","spider","spider","worm","worm","worm","worm","spider")
Numbers <- runif(8)
df <- data.frame(Fruit,Bug,Numbers)

For factor count

bar.plot <- function(dat,j,c){
ggplot(dat, aes(j, ..count..)) + 
geom_bar(aes(fill = c), position = "dodge")
}
bar.plot(df,Fruit,Bug)

I get

Don't know how to automatically pick scale for object of type function. Defaulting to continuous
    Error in eval(expr, envir, enclos) : object 'j' not found

I am mostly concerned about the second line of the error Error in eval... Anyone know why this is happening? I have a lot of bar plots to make so this function would make my life a lot easier.

theamateurdataanalyst
  • 2,794
  • 4
  • 38
  • 72

1 Answers1

4

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)

enter image description here

MrFlick
  • 195,160
  • 17
  • 277
  • 295