2014-07-24 60 views
0

循環多個ggplots我有這個對於R中

Product <- c("X","Y","Z") 
Var1 <- runif(3) 
Var2 <- rnorm(3) 
Var3 <- rnorm(3) 

df <- data.frame(Product,Var1,Var3,Var2) 

bar.plot <- function(dat,k,p,this) { 
    mytitle <- paste("Topic:",as.character(this)) 
    ggplot(dat, aes_string(x = substitute(k), y = substitute(p))) + 
    geom_bar(position = "dodge",stat = "identity",fill="lightblue", colour="black") + 
    theme(plot.title=element_text(size=25,face="bold"), axis.text.y = element_text(size=20),axis.title.y = element_blank(),axis.text.x = element_text(size = 10,angle = 30, hjust = 1)) + 
    labs(title=mytitle) 
} 

我想以下在df返回我的每個列的三個地塊。它並沒有。

col <- c(Var1,Var2,Var3) 
for(i in col){ 
bar.plot(df,Product,i,"Data") 
} 

任何想法,爲什麼這可能是?謝謝。

+0

檢查「col」變量的內容。您應該將「Product」,「Var1」等作爲字符傳遞給ggplot函數調用。 – DrDom

+0

你期望將他們歸還給誰?你似乎沒有試圖將它們存儲在任何地方。 'for'循環不返回值。 – MrFlick

回答

0

正如@DrDom所說,您需要col中的字符,並且如果您想在for循環內看到它們需要的圖形,請使用print。 (或保存,或在list它們分配...)

col <- c("Var1", "Var2", "Var3") 
for(i in col){ 
    print(bar.plot(df, Product, i, "Data")) 
} 

雖然這會工作得很好與你原來的bar.plot,該substitute是完全沒有必要(你已經在使用aes_string!),所以我們可以簡化爲:

bar.plot <- function(dat,k,p,this) { 
    mytitle <- paste("Topic:", as.character(this)) 
    ggplot(dat, aes_string(x = k, y = p)) + 
     geom_bar(position = "dodge", stat = "identity", 
       fill = "lightblue", colour = "black") + 
     theme(plot.title=element_text(size = 25, face = "bold"), 
       axis.text.y = element_text(size = 20), 
       axis.title.y = element_blank(), 
       axis.text.x = element_text(size = 10, angle = 30, hjust = 1)) + 
     labs(title = mytitle) 
} 
+0

hm我得到eval(expr,envir,enclos)中的錯誤:未找到對象'X' – theamateurdataanalyst

0

這是一個稍微不同的方法。

bar.plot <- function(dat,k,p,this) { 
    mytitle <- paste("Topic:",as.character(this)) 
    gg  <- data.frame(x=dat[,k],y=dat[,p]) 
    ggplot(gg, aes(x,y)) + 
    geom_bar(position = "dodge",stat = "identity",fill="lightblue", colour="black") + 
    theme(plot.title=element_text(size=25,face="bold"), axis.text.y = element_text(size=20),axis.title.y = element_blank(),axis.text.x = element_text(size = 10,angle = 30, hjust = 1)) + 
    labs(title=mytitle) 
} 
for(i in 2:4){ 
    print(bar.plot(df,"Product",i,"Data")) 
} 

這將構建與列xy在函數內部的數據幀,並使用在調用ggplot(...),而不是試圖用aes_string(...)

你的代碼:col <- c(Var1,Var2,Var3)創建一個向量長度9,基本連接三個Var列。當你使用for (i in col)時,R將i設置爲col中每個元素的值,所以循環運行9次 - 不是你想要的。