2017-05-14 72 views
-1

我一直在創建一個帶有錯誤條的條形圖來描述我擁有的數據集的組差異。但是,誤差線出現時髦,因爲它們出現在酒吧上方和酒吧中間。在R中創建錯誤條(ggplot2)

我的代碼:

ggplot(MRS_Hippo_NAA_Cre_Data_copy, aes(Type, Hippo_6_9NAACre, fill=Type)) + 
geom_bar(stat="summary", fun.y="mean", colour="black", size=.3) + 
geom_errorbar(aes(ymin=meanNAA-NAAse, ymax=meanNAA+NAAse), width=.2, 
position=position_dodge(.9)) + labs(x="Group", y="Right Posterior NAA/Cre") + 
scale_fill_manual(values=c("#0072B2", "#D55E00"), name="Group") + theme(text = 
element_text(size=18))` 

這產生該曲線圖中:

std <- function(x) sd(x)/sqrt(length(x)) 

X = Hippo_6_9NAACre

plot

我通過使用下面的函數計算的標準誤差

不確定圖表爲什麼會產生時髦的錯誤條。任何人都可以幫助或提供見解?

+0

我猜''meanNAA'和'NAAse'是爲兩個組合。當然,我只是在猜測,因爲沒有可重複的例子。 – Axeman

+0

是的,這是正確的。我應該將它們分開嗎? – erikapnt

回答

1

我最近有一個類似的問題。 爲了解決這個問題,首先你可能想要刪除層

geom_errorbar(aes(ymin=meanNAA-NAAse, 
ymax=meanNAA+NAAse), width=.2, position=position_dodge(.9)) 

和而再次使用與statsummary功能的層。這將生成分組的錯誤欄。 如您想要顯示標準錯誤的橫條,您必須創建一個適當的函數來返回所需的值,例如statsummary。 使用iris數據集查找下面的工作示例。

library(ggplot2) 

## create a function for standard error that can be used with stat_summary 
# I created the function inspecting the results returned by 'mean_cl_normal' that is the   
# function used in some examples of stat_summary (see ?stat_summary). 

mean_se = function(x){ 
se = function(x){sd(x)/sqrt(length(x))} 
data.frame(y=mean(x), ymin=mean(x)+se(x), ymax=mean(x)-se(x)) 
} 

## create the plot 
p = ggplot(iris, aes(x = Species, y = Sepal.Length), stat="identity") + 
stat_summary(fun.y = mean, geom = "col", fill = "White", colour = "Black", width=0.5) + 
stat_summary(fun.data = mean_se, geom = "errorbar", width=0.2, size=1) 

# print the plot 
print(p)