【问题标题】:how to put standard error bars on my ggplot2 2-factor bar graphic?如何在我的 ggplot2 2 因子条形图上放置标准误差线?
【发布时间】:2021-02-25 15:57:54
【问题描述】:

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

这是mean+sd的情节:

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, data=EGG, 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))

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

【问题讨论】:

  • 显然无效...Error in match.fun(FUN) : object 'std.error' not found

标签: r ggplot2 errorbar


【解决方案1】:

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

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, data=EGG, FUN=sd)
ee <- aggregate(chemcon ~ day + type, data=EGG, FUN=std.error)  ##  from library(plotrix)
#ee <- aggregate(chemcon ~ day + type, data=EGG, FUN=sd(x)/sqrt(sum(!is.na(x))) )
# cc <- aggregate(chemcon ~ day + type, data=EGG, 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")

【讨论】:

  • 这真是一个奇迹!非常感谢你,你不知道你帮助了我多少。像你这样的人是我喜欢这个社区的原因。向您致以最诚挚的问候,祝您有美好的一天。
猜你喜欢
  • 1970-01-01
  • 2016-06-09
  • 1970-01-01
  • 2020-02-28
  • 1970-01-01
  • 2017-08-03
  • 2020-09-08
  • 1970-01-01
相关资源
最近更新 更多