首页 > 解决方案 > How do I incorporate SE in place of SD in my bar chart error bars? Also, how do I change the order of my x-axis groups

问题描述

I have created a bar chart displaying proportion of time spent on different behaviours for groups of lemurs. However I am placed with two problems.

1) I had hoped to use standard error bars in place of my standard deviation bars. I am unsure in how to incorporate it into my existing code. My current ggplot output is as follows:

 data_summary <- function(data, varname, groupnames){
  require(plyr)
  summary_func <- function(x, col){
    c(mean = mean(x[[col]], na.rm=TRUE),
      sd = sd(x[[col]], na.rm=TRUE),)
  }
  data_sum<-ddply(data, groupnames, .fun=summary_func,
                  varname)
  data_sum <- rename(data_sum, c("mean" = varname))
  return(data_sum)
}

df4 <- data_summary(mydata_bc, varname="Time", 
                    groupnames=c("Group", "Behaviour"))

p <- ggplot(df4, aes(x=Behaviour, y=Time, fill=Group)) + 
  geom_bar(stat="identity", position=position_dodge()) +
  geom_errorbar(aes(ymin=Time-sd, ymax=Time+sd), width=.2,
                position=position_dodge(0.9))

2) I also had hoped to change the order of my behaviours on the x axis.

Any help would be greatly appreciated.

Current bar chart Current bar chart

My csv data: https://drive.google.com/file/d/1UWJoluv3MWwXoQg2zcDORDJiWuIA8j4f/view?usp=sharing

标签: rerror-handlingbar-chartstandard-deviationerrorbar

解决方案


我更换了:

sd = sd(x[[col]], na.rm=TRUE)

和:

se = sd(x[[col]], na.rm=TRUE) / sqrt(sum(!is.na(x[[col]])))

即 SD 除以长度的平方根。

您的 data_summary 函数中还有一个额外的逗号。

您可以通过重新排序因子来更改列的顺序。

mydata_bc$Behaviour <- factor(mydata_bc$Behaviour, levels = c("Resting","Feeding","Socialising","Locomotion"))

然后你就可以绘图了。

 data_summary <- function(data, varname, groupnames){
  require(plyr)
  summary_func <- function(x, col){
    c(mean = mean(x[[col]], na.rm=TRUE),
      se = sd(x[[col]], na.rm=TRUE) / sqrt(sum(!is.na(x[[col]]))))
  }
  data_sum<-ddply(data, groupnames, .fun=summary_func,
                  varname)
  data_sum <- rename(data_sum, c("mean" = varname))
  return(data_sum)
}

mydata_bc$Behaviour <- factor(mydata_bc$Behaviour, levels = c("Resting","Feeding","Socialising","Locomotion"))

df4 <- data_summary(mydata_bc, varname="Time", 
                    groupnames=c("Group", "Behaviour"))

p <- ggplot(df4, aes(x=Behaviour, y=Time, fill=Group)) + 
  geom_bar(stat="identity", position=position_dodge()) +
  geom_errorbar(aes(ymin=Time-se, ymax=Time+se), width=.2,
                position=position_dodge(0.9))

在此处输入图像描述


推荐阅读