【发布时间】:2019-01-31 22:28:42
【问题描述】:
我有一个关于在循环中生成多个 ggscter 图的问题。 我有一个数据集:
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 个环境因素中的第一个位置绘制。
【问题讨论】:
-
您是否尝试过合并数据并使用
facet_grid或facet_wrap之一?如果没有,您可能需要查看cowplot或gridExtra。 -
我编辑了你的示例数据;其他列下方的列使复制/粘贴变得困难。