2015-05-28 56 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