2013-04-30 32 views
0

所以我用下面的代碼,以生成圖形,其中申請和蘋果產生2個不同的圖形,現在我希望將它們組合成一個單一的圖表結合2個不同的圖形輸出中的R爲一個曲線圖

data <- ddply(data, .(Value), summarise, 
       N = length(means), 
       mean = mean(means), 
       sd = sd(means), 
       se = sd(means)/sqrt(length(means))) 

apple=ggplot(data, aes(x=Value, y=mean)) + 
    geom_errorbar(aes(ymin=mean-se, ymax=mean+se), width=.1) + 
    geom_ribbon(aes(ymin=mean-se, ymax=mean+se),alpha=0.5) + 
    geom_line() + 
    geom_point() 

dat <- ddply(dat1, .(Value), summarise, 
       N = length(means), 
       mean = mean(means), 
       sd = sd(means), 
       se = sd(means)/sqrt(length(means))) 

appl=ggplot(dat, aes(x=Value, y=mean)) + 
    geom_errorbar(aes(ymin=mean-se, ymax=mean+se), width=.1) + 
    geom_ribbon(aes(ymin=mean-se, ymax=mean+se),alpha=0.5) + 
    geom_line() + 
    geom_point() 
+0

通過「合併成一個繪圖」,你究竟意味着什麼? – 2013-04-30 17:15:06

+0

我想讓兩個散點圖在同一個圖中 – 2013-04-30 17:17:44

回答

1

答案是將數據集組合成一個大數據集,並附加一列指定該子集所屬的數據集。沒有必要單獨創建繪圖並將它們組合在一起。假設該列名爲id,那麼您可以在aes中使用附加參數以使圖表起作用,即aes(x=Value, y=mean, color=id)。結合數據集可以使用rbind完成。

一個代碼示例:

df1 = data.frame(Value = sample(LETTERS[1:8], 1000, replace = TRUE), 
       means = runif(1000)) 
df2 = data.frame(Value = sample(LETTERS[1:8], 1000, replace = TRUE), 
       means = runif(1000) + 0.5) 
df1 = ddply(df1, .(Value), summarise, 
       N = length(means), 
       mean = mean(means), 
       sd = sd(means), 
       se = sd(means)/sqrt(length(means))) 
df1$id = "ID1" 
df2 = ddply(df2, .(Value), summarise, 
       N = length(means), 
       mean = mean(means), 
       sd = sd(means), 
       se = sd(means)/sqrt(length(means))) 
df2$id = "ID2" 
df_all = rbind(df1, df2) 
ggplot(df_all, aes(x=Value, y=mean, color = id)) + 
    geom_errorbar(aes(ymin=mean-se, ymax=mean+se), width=.1) + 
    geom_ribbon(aes(ymin=mean-se, ymax=mean+se),alpha=0.5) + 
    geom_line() + 
    geom_point() 

導致如下圖:

enter image description here

注意,我不得不編造一些數據由於缺乏數據。例如,形成你的身邊,所以這可能不完全適合你的情況。不過,它很好地說明了這種方法。

+0

這兩個圖有不同的標準錯誤......我將如何合併它? – 2013-04-30 17:26:12

+0

組合數據集並正確設置'aes'後,所有內容都會自動更正。試試看看。如果你的例子是可重現的,即提供給我數據,我可以爲你提供一個工作示例。 – 2013-04-30 17:27:31

+0

更容易,'ggplot2'對每個圖層都有一個可選的'data'參數,所以你可以添加一個新的圖層和第二個數據集。 – baptiste 2013-04-30 17:34:51

相關問題