微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在我的 ggplot2 2 因子条形图上放置标准误差条?

如何解决如何在我的 ggplot2 2 因子条形图上放置标准误差条?

我一直在尝试将当前的标准偏差条更改为条形图中的标准误差条。

这是均值+标准差的图:

EGG <- data.frame(type = c("this","this","that","that"),chemcon = c(10,11,12,13),day = c("Monday","Tuesday","Monday","Tuesday"))

EGG
#>    type chemcon     day
#> 1  this      10  Monday
#> 2  this      11 Tuesday
#> 3  that      12  Monday
#> 4  that      13 Tuesday

require(ggplot2)
aa <- aggregate(chemcon ~ day + type,data=EGG,FUN=mean)
bb <- aggregate(chemcon ~ day + type,FUN=sd)
cc <- merge(aa,bb,by=c("day","type"))
colnames(cc)[3:4] <- c("mean","sd")

ggplot(cc,aes(x = type,y = mean,fill = day))+
  geom_bar(stat="identity",position= "dodge") + #nb you can just use 'dodge' in barplots
  scale_fill_brewer(palette="Paired")+
  theme_minimal() +
  labs(x="",y="chemcon") +
  theme(panel.background = element_blank(),axis.line = element_line(colour = "black"),panel.grid=element_blank()) +
  geom_errorbar(aes(ymin = mean-sd,ymax = mean+sd),position = "dodge")

我尝试用“se”替换“sd”的聚合函数(FUN),没有运气,然后我尝试创建“se”也没有运气:

se = sd(Egg$chemcon) / sqrt(length(Egg$chemcon))

问题是因为我必须保持“聚合”函数,因为它在尝试表示双因子条形图时效果最佳,但我还没有看到有人像这样在其他任何地方使用它并带有标准错误。有人可以帮助我了解我缺少什么吗?

解决方法

尝试 std.error() 包中的 plotrix,如下所示

library(plotrix)
library(ggplot2)
EGG <- data.frame(type = rep(c("this","this","that","that"),2),chemcon = c(10,11,12,13,14,15,16,17),day = rep(c("Monday","Tuesday"),4))

EGG

aa <- aggregate(chemcon ~ day + type,data=EGG,FUN=mean)
bb <- aggregate(chemcon ~ day + type,FUN=sd)
ee <- aggregate(chemcon ~ day + type,FUN=std.error)  ##  from library(plotrix)
#ee <- aggregate(chemcon ~ day + type,FUN=sd(x)/sqrt(sum(!is.na(x))) )
# cc <- aggregate(chemcon ~ day + type,FUN = function(x) c(mean = mean(x),sd = sd(x),se = (sd(x)/sqrt(sum(!is.na(x)))) ))
cc <- merge(aa,ee,by=c("day","type"))
colnames(cc)[3:4] <- c("mean","se")


ggplot(cc,aes(x = type,y = mean,fill = day))+
  geom_bar(stat="identity",position= "dodge") + #nb you can just use 'dodge' in barplots
  scale_fill_brewer(palette="Paired")+
  theme_minimal() +
  labs(x="",y="chemcon") +
  theme(panel.background = element_blank(),axis.line = element_line(colour = "black"),panel.grid=element_blank()) +
  geom_errorbar(aes(ymin = mean-se,ymax = mean+se),position = "dodge")

output

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。