[英]How to plot multiple group means and the confidence intervals in ggplot2 (R)?
我有看起來像這樣的數據:
A B C
8 5 2
9 3 1
1 2 3
3 1 2
4 3 1
我需要使用ggplot2繪制每個平均值的平均值以及置信區間。 我也想從數據本身獲取置信區間(例如,使用stat_summary(fun.data = mean_cl)),但是我不確定如何繪制這種格式的數據均值。
我嘗試了以下代碼,但無法運行。 我不確定第2行中的y需要輸入什么。
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
您的數據不是長格式,這意味着它應如下所示:
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
之前的手工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)
這給出了附件圖。
就像David所說的那樣,您首先需要長格式,但是您應該能夠使用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")
如果要手動建立相同的時間間隔,則需要lm
和confint
才能獲得所需的信息:
mod <- lm(value ~ 0 + key, data = dat)
ci <- confint(mod)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.