2014-07-23 94 views
2

出於某種原因,一個功能,當我做到以下幾點:創建使用GGPLOT2

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) 

對於係數計

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

我得到

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 

我主要關注的是第二錯誤的線在eval中...任何人都知道爲什麼會發生這種情況?我有很多棒圖,所以這個功能會讓我的生活變得更輕鬆。

回答

4

感謝ggplot的非標準評估,您不能像ggplot函數那樣傳遞符號名稱。直到你實際上print()的情節,aes才被評估。這就是爲什麼

bb<-bar.plot(df,Fruit,Bug) 

不會給出同樣的錯誤。但是在那個時候,住在函數內部的變量j不再存在。如果要動態指定要用作aes()表達式中的值的數據列,則應使用aes_string。如果您希望能夠傳遞符號名稱而不是字符串,則可以使用substitute將它們轉換爲字符。例如,這將工作

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