2015-05-28 48 views
0

我有一个数据帧(可以转换为阵列,反之亦然为了方便的任务),其看起来像迭代绘制数据帧与ggplot中的R

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到在由列FACTOR,例如VAL1~VAL2VAL1~VAL3VAL~VAL4VAL2~VAL3VAL2~VAL4VAL3~VAL4值分解所有组合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) 

当我执行这个,我没有得到任何结果,除了一些错误,如

mapping: colour = factor(FACTOR) 
geom_point: na.rm = FALSE 
stat_identity: 
position_identity: (width = NULL, height = NULL) 

有一个简单的办法呢?

+1

将'plots'设置为'list()',而不是'vector()'。你不需要'union()',只需'c()'。 – Gregor

+0

我想将所有图形追加到列表中。所以结合。 – Vignesh

+0

我明白你想要做什么。 “工会”对它来说是一个糟糕的工具。你应该有'plots = list()',然后'plots = c(图,ggplot(...))'。或者甚至更好''[[i]] = ggplot(...)''。 – Gregor

回答

0

对于此解决方案,我使用dplyrtidyr对数据进行了整形,然后使用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() 

注意我的观点是在不同的地方,因为我产生了假数据。 enter image description here