我有一个关于在循环中生成多个ggscater图的问题。 我有一个数据集:
dput(head(data_1))
structure(list(pop.id = c("pop1", "pop2", "pop3", "pop4", "pop5",
"pop6"), pos_1 = c(0.75, 0.95, 0.75, 0.7, 1, 1), pos_2 = c(0,
0, 0.05, 0, 0, 0), pos_3 = c(0L, 0L, 0L, 0L, 0L, 0L), pos_4 = c(0L,
0L, 0L, 0L, 0L, 0L), pos_5 = c(0L, 0L, 0L, 0L, 0L, 0L), pos_6 = c(0.05,
0.05, 0, 0, 0.15, 0.05), pos_7 = c(0L, 0L, 0L, 0L, 0L, 0L), Latitude_e =
c(1.868536,
1.627792, 1.489075, 1.816299, 1.642119, 1.433996), Longitude_e = c(-0.5019046,
-0.6238463, -0.6386181, -0.5478555, -0.5133615, -0.4472022),
Elevation_e = c(2.183258, 2.006655, 1.565147, 2.337786, 1.543071,
1.454769), MAT_e = c(-1.919178, -1.648235, -1.377292, -1.919178,
-1.648235, -1.241821), MWMT_e = c(-0.24204516, -0.24204516,
-0.24204516, -0.24204516, -0.24204516, 0.06051129), MCMT_e = c(-2.031283,
-1.691319, -1.436346, -2.031283, -1.691319, -1.351355), TD_e = c(2.085645,
1.723449, 1.542351, 2.085645, 1.723449, 1.451802), MAP_e = c(0.9177859,
0.6161032, 0.5155423, 0.8775616, 0.6864958, 0.5255984), MSP_e = c(-0.393691,
-0.418043, -0.2962829, -0.393691, -0.3449869, -0.2719309),
AHM_e = c(-1.008593, -0.774882, -0.6813975, -0.9930123, -0.8216242,
-0.6658168), SHM_e = c(0.2504209, 0.2654162, 0.1754446, 0.2504209,
0.2054351, 0.1604493), DD_0_e = c(2.235186, 1.82631, 1.417435,
2.235186, 1.82631, 1.417435), DD5_e = c(-1.926029, -1.606345,
-1.360735, -1.965015, -1.602447, -1.239879), DD_18_e = c(2.10857,
1.718094, 1.457777, 2.146852, 1.718094, 1.335274)), class = "data.frame",
row.names = c(NA, -6L))
我正在尝试为所有环境变量(latitude_e,...)上的每个位置(pos_1 ... pop_7)生成一些散点图。 我想将每个位置的这些图保存在单独的文件中。这意味着我应该得到7个文件(因为总共有7个位置),每个文件包含11个图(因为它们是11个环境变量)。这是我正在使用的代码,但没有给我想要的输出。如果有人可以帮助我解决此问题,我将不胜感激!
这是我到目前为止使用的代码:
test_type_env_inv<-array ("0",ncol (data_1))
env_type<-grep ("e",colnames(data_1))
inv_type<-grep ("pos",colnames(data_1))
the_e<-colnames(data_1[env_type])
the_i<-colnames(data_1[inv_type])
#pdf(file="annuus_part5.pdf", height= 15, width = 15)
plots <- list()
for (i in 1:11){
for (j in 1:7){
y<-max(data_1[,the_i[j]])+0.3
x<-min(data_1[,the_i[i]])+ (-1)
sp<-print(ggscatter(data_1, x = the_e[i], y = the_i[j],
add = "reg.line", # Add regressin line
add.params = list(color = "blue", fill = "lightgray"), # Customize reg. line
conf.int = TRUE)
+ stat_cor(method = "pearson", label.x = x, label.y = y))
}
plots[[i]] <- sp
}
multiplot(plotlist = plots, cols = 4)
这是图表,我的代码仅针对7个环境因素中的第一个位置绘制。
答案 0 :(得分:1)
您可以使用\packages
库将每个位置的图(即 pos _ * 变量)与所有环境变量(即 * _ e 变量)合并,方法是:使用地块清单。每个位置只有一个绘图时,可以使用 for-loop :
.sln
然后,所有图都将在您的工作目录中可用:
cowplot