簡體   English   中英

R中多個ggplots的For循環

[英]For loop for multiple ggplots in 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")
}

任何想法為什么會這樣? 謝謝。

正如@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)
}

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

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次-而不是您想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM