2017-05-14 111 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)