用ggplot在R中迭代绘制数据帧
我有一个数据帧(可以转换为数组,反之亦然,以方便任务),如下所示用ggplot在R中迭代绘制数据帧,r,ggplot2,R,Ggplot2,我有一个数据帧(可以转换为数组,反之亦然,以方便任务),如下所示 ID FACTOR VAL1 VAL2 VAL3 VAL4 Apple Fruits 0.0056 -0.0025 0.0039 -0.0037 Orange Fruits 0.0067 -0.0039 0.0023 -0.0021 Carrot Veggies 0.008 -0.0037 0.0095 -0.007 Spinach Veggies 0.0067 -
ID FACTOR VAL1 VAL2 VAL3 VAL4
Apple Fruits 0.0056 -0.0025 0.0039 -0.0037
Orange Fruits 0.0067 -0.0039 0.0023 -0.0021
Carrot Veggies 0.008 -0.0037 0.0095 -0.007
Spinach Veggies 0.0067 -0.0086 0.0024 -0.0042
Cucumber Veggies 0.0056 -0.0049 -0.0202 -0.0099
Grapes Fruits 0.0055 -0.0044 0.0028 -0.0049
我希望能够将VAL1
绘制到VAL4
,以列FACTOR
的值为因数的所有组合,例如VAL1~VAL2
,VAL1~VAL3
,VAL~VAL4
,VAL2~VAL3
,VAL2~VAL4
,VAL3~VAL4
,ggplot
中的所有水果或蔬菜因素
此数据位于data.txt文件中
我的代码:
val = read.table("data.txt",sep="\t",header=TRUE)
df_val<-as.data.frame(val)
headers<-vector()
for (name in names(df_val)) {
headers<-union(headers,c(name))
}
plots<- vector()
for (i in 3:5) {
plots=union(plots,c(ggplot(df_val, aes(headers[i], headers[i+1])) + geom_point(aes(colour = factor(FACTOR)))))
}
multiplot(plots,cols=3)
有一种简单的方法吗?对于这个解决方案,我使用
dplyr
和tidyr
对数据进行了整形,然后使用ggplot2
中的面绘制组合。这不需要在最后将多个绘图合并为一个
library(dplyr)
library(tidyr)
library(ggplot2)
# Index of VALi
val_i <- 1:4
# Shape the data as y ~ x
combos <- lapply(val_i[-max(val_i)], function(i) {
df_val %>%
gather_("x_key", "x", paste0("VAL", (i + 1):max(val_i))) %>%
mutate(y_key = paste0("VAL", i),
x_key = as.character(x_key)) %>%
unite(combo, y_key, x_key, sep = " ~ ") %>%
select_("ID", "FACTOR", "combo", y = paste0("VAL", i), "x")
})
combos <- bind_rows(combos)
# Plot using facets
ggplot(combos, aes(x = x, y = y, color = FACTOR)) +
facet_wrap(~combo, ncol = 3, scales = "free") +
geom_point()
库(dplyr)
图书馆(tidyr)
图书馆(GG2)
#VALi指数
瓦卢i%
突变(y_键=paste0(“VAL”,i),
x_-key=as.character(x_-key))%>%
联合(组合键,y键,x键,sep=“~”)%>%
选择“ID”、“FACTOR”、“combo”,y=paste0(“VAL”,i),“x”)
})
组合使绘图成为列表()
,而不是向量()
。您不需要union()
,只需要c()
。我正在尝试将所有图形附加到列表中。所以联盟,我明白你想做什么<代码>联合
是一个糟糕的工具。您应该有plots=list()
,然后是plots=c(plots,ggplot(…)
。或者更好的plots[[i]]=ggplot(…)
。我还想你应该使用aes\u string()
,而不是aes()!但是当我试图得到所有带有两个for循环的组合时,我得到了相同的错误集图
library(dplyr)
library(tidyr)
library(ggplot2)
# Index of VALi
val_i <- 1:4
# Shape the data as y ~ x
combos <- lapply(val_i[-max(val_i)], function(i) {
df_val %>%
gather_("x_key", "x", paste0("VAL", (i + 1):max(val_i))) %>%
mutate(y_key = paste0("VAL", i),
x_key = as.character(x_key)) %>%
unite(combo, y_key, x_key, sep = " ~ ") %>%
select_("ID", "FACTOR", "combo", y = paste0("VAL", i), "x")
})
combos <- bind_rows(combos)
# Plot using facets
ggplot(combos, aes(x = x, y = y, color = FACTOR)) +
facet_wrap(~combo, ncol = 3, scales = "free") +
geom_point()