简体   繁体   中英

How to plot error bars for grouped bar chart using ggplot2?

I have a data set with two different factors (Place and Value) for one variable (bTemp) and I grouped the data based on the two factors, then generated the standard error (sem) for these data groups (ie I generated the st. error for data under field max, lab max, field min, etc.).

I tried to plot the st. errors of the grouped data onto my grouped bar chart, but I am only getting one st. error bar for each cluster of mean bars rather than two (one for each mean bar in the cluster). I checked my grouped data frame and it is generating the st. errors properly. So there must be something wrong with how I am defining the error bars in geom_errorbar. 在此处输入图像描述

 str(LabFieldData)
'data.frame':   324 obs. of  3 variables:
 $ Place: Factor w/ 2 levels "Field","Lab": 1 1 1 1 1 1 1 1 1 1 ...
 $ Value: Factor w/ 3 levels "Max","Mean","Min": 3 3 3 3 3 3 3 3 3 3 ...
 $ bTemp: num  26.5 26.7 26.1 28.1 26.6 26.8 23.9 26.1 28.5 26.4 ...

#Group data by place (lab,field) and value(min,mean,max)
LabFieldData %>% group_by(Place,Value) %>% 
  mutate(sem = sd(bTemp)/sqrt(length(bTemp))) %>%

#Plot bar plot of means by value (mean, min, max) and color by place (lab, field)
ggplot(mapping = aes(Value, bTemp, color = Place)) +
  geom_bar(mapping = aes(color = Place, fill = Place), stat = "summary", position="dodge") +
  geom_errorbar(stat = 'summary', mapping = aes(ymin=bTemp-sem,ymax=bTemp+sem),
    position=position_dodge(0.9),width=.1, color = "black", size = 1) + 
  scale_y_continuous(name = "Body Temperature (°C)", breaks = c(0,5,10,15,20,25,30,35),
    limits=c(0,34)) + scale_x_discrete(name=element_blank(),limits=c("Min","Mean","Max")) +
  theme(legend.title = element_blank()) + scale_color_hue()

You were very close, you need to specify the fill in the ggplot function and not in the geom_bar function.

LabFieldData %>% group_by(Place,Value) %>% 
   mutate(sem = sd(bTemp)/sqrt(length(bTemp))) %>%
   #Plot bar plot of means by value (mean, min, max) and color by place (lab, field)
   ggplot(mapping = aes(Value, bTemp, color = Place, fill=Place)) +
   geom_bar(stat = "summary", position="dodge") +
   geom_errorbar(stat = 'summary', mapping = aes(ymin=bTemp-sem,ymax=bTemp+sem),
                 position=position_dodge(0.9), width=.1, color = "black", size = 1) + 
   scale_y_continuous(name = "Body Temperature (°C)", breaks = c(0,5,10,15,20,25,30,35), limits=c(0,34)) + 
   scale_x_discrete(name=element_blank(), limits=c("Min","Mean","Max")) +
   theme(legend.title = element_blank()) + scale_color_hue()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM