将for循环生成的多个ggplots放入一个图像

时间:2020-02-08 11:43:20

标签: r for-loop ggplot2 plot

第一次问一个问题,如果我错过任何重要的细节,请先道歉。我对R还是很陌生,但是随着我学到更多,我将尽自己的一份力。同时希望有人可以提供帮助。

我有一个for循环,可以从我的数据中生成多个图。情节本身是完美的,但是,我很难将情节1到4添加到单个图像中。

如果我使用的是plot(),我可以使用par(mfrow - c(1,2,3,4),但是当我向每个图添加多个数据帧时,即ggplot中的多个geom_point(),我认为我无法做到这一点

我的数据看起来像这样,但更长了,线N01,N02等的多个数据点,我正在用N01,N02等的数据生成新图,并覆盖WT1和WT2点。

我认为我可能需要将循环的每次迭代保存到新变量中,然后使用multiplot()来获得所需的结果。

如果我想出答案,我会发表,但是如果有人殴打我,请先谢谢你。

N01 N01.01  0.0 7693
2   N01 N01.02  2.0 3404
3   N01 N01.03  2.0 3404
4   N01 N01.04  1.0 6395
5   N01 N01.05  1.0 5171
6   N01 N01.06  2.0 6001
7   N01 N01.07  1.0 6671
8   N01 N01.08  1.5 6700
9   N01 N01.09  1.0 9060
10  N04 N04.01  2.0 6857
11  N04 N04.02  4.0 10378

setwd ("C:/Users/HP/Desktop/Studio R/Patty")
df <- read.csv("Data/Raw V2.csv")

#need to create a new data frame with a new coluum taking information from another column
df2 <- split(df, df$ï..ID)
x1 <- df2$WT1[,3:4] #new var for the wild type that wants plotting on all the charts
x2 <- df2$WT6[,3:4]

plot_list <- list() #creates an empty list to save the plots in


for (i in 1:length(df2)){
  z1 <- df2[[i]][,3:4]#new var from the data fram i amount of times using data from column 3 to 4
  title <- (df2[[i]][,1][1]) #used later on to add the title variable in the legend
  par(mar=c(4,4,1,1), mfrow=c(2,2))
  f <- 
    ggplot(data=z1, aes(x=copies, y=leaf_area)) + 
    geom_point(aes(col="black"))+ #creates the plots of i
    geom_point(data=x1, aes(col="blue"))+  #adds the wt to all plots, aes neeeded to create legend
    geom_point(data=x2, aes(col="red"))+
    theme(panel.background = element_blank(), axis.line = element_line(colour = "black"),
          panel.grid.minor = element_line())+
    scale_color_identity(name = "", breaks = c("black", "blue", "red"), labels = c(paste0("(",title,")"),("(WT1)"),("(WT6)")), guide = "legend")+
    theme(legend.position = c(0.95, 0.95), legend.justification = c("right", "top"), legend.direction = "horizontal")+
    scale_x_continuous(limits = c(0, 4)) + #standarsises the axis
    scale_y_continuous(limits = c(0, 12000)) +
    xlab(bquote("Number of Inserts"))+
    ylab(bquote("Leaf Area (mm'^2')"))+
    ggtitle(df2[[i]][,1][1])
    plot_list[[i]] <- f
    list2env(plot_list[[i]], envir = globalenv()) #send the list to the global environment
}

在理想的世界中,这本来可以工作的:

for (i in plot_list){
  par(mfrow = c(2,2))
  plot(i)
}

2 个答案:

答案 0 :(得分:1)

您正尝试使用par(mfrow=...),但这仅适用于基本R图。对于ggplot,如果您喜欢类似的内容,则可以使用gridExtra,因为您已经有一个绘图列表。您可以在下面使用iris

查看示例

另外,作为注释,很可能您不需要使用list2env,因为您已经分配了它

library(ggplot2)
library(gridExtra)

plot_list <- list() 
df <- split(iris,iris$Species)

for(i in seq_along(df)){
plot_list[[i]] <- ggplot(df[[i]],aes(x=Sepal.Length,y=Sepal.Width))+
geom_point()+
ggtitle(names(df)[i])
}

grid.arrange(grobs=plot_list,ncol=2)

enter image description here

我看到您经常想将其作为参考。我将模拟看起来像您的数据的东西:

set.seed(100)
WT1 <- data.frame(Sepal.Length=seq(4,6.5,length.out=50),
Sepal.Width=seq(1.5,3,length.out=50)+rnorm(50,0.5,0.2),Species="WT1")
WT2 <- data.frame(Sepal.Length=seq(6,8,length.out=50),
Sepal.Width=seq(2,4.5,length.out=50)+rnorm(50,0.5,0.2),Species="WT2")

df <- rbind(iris[,c("Sepal.Length","Sepal.Width","Species")],WT1,WT2)
colnames(df)[3] <- "ID"

现在我们绘图:

# separate the two datasets you want:
obs <- droplevels(subset(df,!ID %in% c("WT1","WT2")))
ref <- droplevels(subset(df,ID %in% c("WT1","WT2")))

plot_list <- list() 
for(i in unique(obs$ID)){

thisDF <- rbind(subset(obs,ID==i),ref)
g <- ggplot(thisDF,aes(x=Sepal.Length,y=Sepal.Width,col=ID))+
geom_point() + theme(legend.position = c(0.9,0.9), 
legend.justification = c("right", "top"), 
legend.direction = "horizontal")+ggtitle(i)
plot_list[[i]] <- g
}
grid.arrange(grobs=plot_list,ncol=2)

enter image description here

答案 1 :(得分:1)

感谢@StupidWolf,这是一个巨大的帮助,并且提供了一种更加优雅的做事方式,

我确实找到了一种变通方法,尽管它很笨拙,但对某人可能有用。

首先我删除了

plot_list[[i]] <- f

list2env(plot_list[[i]], envir = globalenv())

然后从循环内部

我在循环中添加了以下内容:

nam <- paste("A", i, sep ="")

循环的每次迭代输出A1,A2,A3

assign(nam, f)

为每次迭代创建一个新变量(f是循环的ggplot输出)

在循环之外,我添加了:

figure1 <- ggarrange(A1, A2, A3, A4, ncol = 2, nrow = 2)

figure2 <- ggarrange(A5, A6, A7, A8, ncol = 2, nrow = 2)

ggarrange允许您将多个图分配给一个窗口

如果您有20多个输出,则可能会在另一个for循环中进行。

再一次,向@StupiudWolf喊出更好的代码。