保存循环功能的grobs

时间:2014-10-16 07:49:25

标签: r function for-loop ggplot2 gridextra

我做了这个长函数,以一个grob figure(3 ggplots)结束。但是,当我在循环中使用此函数并尝试将所有生成的grob放入一个超级数字时,我遇到了问题。我获得了一个有很多凹凸的图形,但它总是相同的凹凸(第一个)!

为了证明我的问题,我做了这个简化的例子:

library(ggplot2)
library(gridExtra)

data(iris)

#the function
multi.plot=function(data,heading){
  p1=ggplot(data,aes(x=Sepal.Length,y=Sepal.Width))+geom_point()+ggtitle(heading)
  p2=ggplot(data,aes(x=Petal.Length,y=Sepal.Width))+geom_point()
  p3=ggplot(data,aes(x=Sepal.Length,y=Petal.Width))+geom_point()
  grob1=arrangeGrob(p1,ncol=2)
  grob2=arrangeGrob(p3,p2,ncol=2)
  grob3=arrangeGrob(grob1,grob2)
  # grob3  / return(grob3)  / print(grob3)   => all tried but non of them helps
}

# the loop
list.grob=list()
for(i in unique(iris$Species)){
  select=iris[iris$Species==i,]
  multi.plot(data=select,heading=i)
  list.grob[[which(unique(iris$Species)==i)]]=grob3  
}

# the final figure
png(file="superplot.png")
do.call("grid.arrange", list.grob)  
dev.off()

那么如何使用函数和循环制作包含大量凹凸的图形?此外,我的标题(“标题”)没有出现应有的情况。

感谢您的任何建议!

2 个答案:

答案 0 :(得分:2)

坚持这样做的技巧,我会继续:

library(ggplot2)
library(gridExtra)
data(iris)

功能

multi.plot=function(data=iris, heading="virginica"){ p1=ggplot(data,aes(x=Sepal.Length,y=Sepal.Width))+geom_point()+ ggtitle(heading) p2=ggplot(data,aes(x=Petal.Length,y=Sepal.Width))+geom_point()+ ggtitle(heading) p3=ggplot(data,aes(x=Sepal.Length,y=Petal.Width))+geom_point()+ ggtitle(heading) grob_all=arrangeGrob(p1, p2, p3, ncol=3) return(grob_all)}

grob_test <- multi.plot()

循环

list.grob=list() names(list.grob) <- unique(iris$Species)

for(i in unique(iris$Species)){ select <- iris[iris$Species==i,] grob_i <- multi.plot(data=select,heading=i) list.grob[[i]]=grob_i}

最后的数字

png(file="superplot.png") do.call("grid.arrange", list.grob)
dev.off()

答案 1 :(得分:1)

此处无需使用for循环。我的意思是更好地通过使用by的物种组来做到这一点,例如:

by(iris,iris$Species,
   function(select)
     multi.plot(data=select,heading=unique(select$Species)))

此外,您应该简化multi.plot功能:

#the function
multi.plot=function(data,heading){
  p1=ggplot(data,aes(x=Sepal.Length,y=Sepal.Width))+geom_point()+ggtitle(heading)
  p2=ggplot(data,aes(x=Petal.Length,y=Sepal.Width))+geom_point()
  p3=ggplot(data,aes(x=Sepal.Length,y=Petal.Width))+geom_point()
  arrangeGrob(p1,arrangeGrob(p1,p2,ncol=2))
}