2016-12-08 222 views
-1

我有一個看起來像這樣的數據:如何繪製ggplot2(R)中的多組平均值和置信區間?

A B C 
8 5 2 
9 3 1 
1 2 3 
3 1 2 
4 3 1 

我需要繪製每個這些手段用GGPLOT2置信區間一起。我也想從數據iteself中獲得置信區間(例如,使用stat_summary(fun.data = mean_cl),但是我不確定如何繪製這種格式的數據的手段。 。下面的代碼,但它不跑,我不知道什麼需要進入在y在第2行

pd <- position_dodge(0.78) 
ggplot(dat, y = c(dat$A,dat$B,dat$C) + ylim(0,10) + theme_bw()) + 
    stat_summary(geom="bar", fun.y=mean, position = "dodge") + 
    stat_summary(geom="errorbar", fun.data=mean_cl_normal, position = pd) 

我得到以下錯誤:

Warning messages: 
1: Computation failed in `stat_summary()`: 
object 'x' not found 
2: Computation failed in `stat_summary()`: 
object 'x' not found 
+0

我已經更新了我的答案 – BioBuilder

+0

你似乎缺少a)ggplot()..也請通過消除所有主題等使這個最小的可重複的例子。還有什麼版本的ggplot2你? – Elin

+0

@Elin:我做了更新。我正在使用ggplot2 2.1.0 – BioBuilder

回答

1

像大衛說,你需要長格式第一,但你應該能夠使用fun.data = "mean_cl_normal"或插入不同的人就好了這樣的:

library(tidyr); library(ggplot2) 
dat <- gather(dat) # gather to long form 

ggplot(data = dat, aes(x = key, y = value)) + 
    geom_point(size = 4, alpha = .5) + # always plot the raw data 
    stat_summary(fun.data = "mean_cl_normal", geom = "crossbar") + 
    labs(title = "95% Mean Confidence Intervals") 

enter image description here

如果您想要手動建立相同的時間間隔,所有您需要的是lmconfint以獲取您之後的信息:

mod <- lm(value ~ 0 + key, data = dat) 
ci <- confint(mod) 
+0

非常好的解決方案彌敦道! 注意'mean_cl_normal'中的參數是如何匹配的。錯誤「object'x'not found」意味着ggplot沒有變量「x」來評估。上面的Nathan代碼顯示ggplot是'x = key'和'y = value',因此它可以在'stat_summary'中評估它。 – David

+0

感謝David,stat_summary的默認'fun.data'是「mean_se」,所以如果你想複製沒有ddply的例子,你可以直接調用'stat_summary(group = something appropriate,geom =「errorbar」)''。超級好的快速viz – Nate

5

你的數據不長格式,這意味着它應該看起來像這樣:

thing<-data.frame(Group=factor(rep(c("A","B","C"),5)), 
        Y = c(8,9,1,3,4, 
         5,3,2,1,3, 
         2,1,3,2,1) 
       ) 

您可以使用像melt()這樣的功能來幫助獲取reshape2包中格式化的數據。

一旦你有了這些,你也必須計算你的數據的手段和SE(ggplot之前的手或stat_summary,ggplot內的正確表達式)。您可能已從示例中複製/粘貼,因爲您正在使用的功能(例如mean_cl_normal)可能未定義。

那我們就手動做吧。

library(plyr) 

cdata <- ddply(thing, "Group", summarise, 
       N = length(Y), 
       mean = mean(Y), 
       sd = sd(Y), 
       se = sd/sqrt(N) 
) 
cdata 

#Group N mean  sd  se 
#1  A 5 4.0 2.236068 1.000000 
#2  B 5 3.8 3.033150 1.356466 
#3  C 5 1.8 1.788854 0.800000 

現在您可以使用ggplot

pd <- position_dodge(0.78) 

ggplot(cdata, aes(x=Group, y = mean, group = Group)) + 
    #draws the means 
     geom_point(position=pd) + 
    #draws the CI error bars 
     geom_errorbar(data=cdata, aes(ymin=mean-2*se, ymax=mean+2*se, 
     color=Group), width=.1, position=pd) 

這給出了附圖。

Mean and CI Plot