Hallie Sheikh
Hallie Sheikh

Reputation: 431

How to plot standard error bars from a dataframe?

I am trying to plot a grouped bar plot of 2 variables GPP and NPP with standard error bars. I have calculated the Standard error for each value in SEGPP and SENPP. How can I plot these standard error bars in the bar group plot?

  Dataset<- c("MOD", "IP", "MP","CC")
GPP <- c(0.6922179, 0.848324, 0.8363999,0.8783096)
NPP<-c(0.4010816,0.4290893, 0.4197423,0.4368065)
df <- data.frame(Dataset,GPP,NPP)
df.m<-reshape2::melt(df)
SEGPP<-c(0.25, 0.15,0.16,0.16)
SENPP<-c(0.15, 0.06,0.08,0.07)
df.m$SEGPP<-c(0.25, 0.15,0.16,0.16)
df.m$SENPP<-c(0.15, 0.06,0.08,0.07)

SDGPP and SDNPP refers to the standard deviation values and SEGPP and SENPP refers to standard error values.

Through this code I can only plot standard error either for GPP or NPP

ggplot(data=df.m,aes(x = factor(Dataset,levels=c('MOD', 'IP', 'MP', 'CC')), y = value, fill = variable))+
  geom_bar(stat="identity", position = "dodge")+
  geom_errorbar(aes(x=Dataset, **ymin=value-SENPP, ymax=value+SENPP**), width=0.4, position = position_dodge(.9))+
  scale_fill_manual(labels = c("GPP", "NPP"),values=cbp1)+
  theme_bw()+
  theme(legend.text=element_text(size=12),axis.text.y=element_text(size=15),
        axis.text.x=element_text(size=12),axis.title.x = element_text(size = 12),
        axis.title.y = element_text(size = 12))+theme(legend.title =element_blank())+
  labs(y= fn, x = "")

How can I plot error bars for both variables in the same plot?

Upvotes: 1

Views: 207

Answers (1)

nniloc
nniloc

Reputation: 4243

I think the trick here is you need to have a single SE column.

Dataset<- c("MOD", "IP", "MP","CC")
GPP <- c(0.6922179, 0.848324, 0.8363999,0.8783096)
NPP<-c(0.4010816,0.4290893, 0.4197423,0.4368065)
df <- data.frame(Dataset,GPP,NPP)
df.m<-reshape2::melt(df)

SEGPP<-c(0.25, 0.15,0.16,0.16)
SENPP<-c(0.15, 0.06,0.08,0.07)
df.m$SE <- c(SEGPP, SENPP)

And then to make the plot you can use geom_errorbar where ymin and ymax are defined as the value plus the SE. Using position_dodge(0.9) to align the SE lines with the bars is talked about in this answer.

ggplot(df.m, aes(Dataset, value, fill = variable)) +
  geom_bar(stat = 'identity', position = position_dodge()) +
  geom_errorbar(aes(ymin = value - SE, ymax = value + SE), position = position_dodge(0.9), width = 0.25)

enter image description here

Upvotes: 3

Related Questions