rggplot2bar-charterrorbar

How do i add seperate error bars for a column plot displaying means in ggplot2


Let's say my data frame was created like this:

df=data.frame(type=as.factor(c("tree","tree","tree","tree", "bush","bush","bush", "bush","flower", "flower", "flower", "flower")),
              age=as.factor(c(5,1,5,1,5,1,5,1,5,1,5,1)),
              size=c(11,3,16,5,2,0.5,3,0.4,1,0.2,0.9,0.15))

and now it looks like that:

> df
     type age  size
1    tree   5 11.00
2    tree   1  3.00
3    tree   5 16.00
4    tree   1  5.00
5    bush   5  2.00
6    bush   1  0.50
7    bush   5  3.00
8    bush   1  0.40
9  flower   5  1.00
10 flower   1  0.20
11 flower   5  0.90
12 flower   1  0.15

I want my x axis to compare the age factor 5 and 1, while having the type factor next to each other.

plot = ggplot(data = df, aes(x = age, y = size, fill=type))
plot = plot + geom_col(position = "dodge")
plot

so far so good

Now I'm really struggling with applying sensibles error bars to my columns using geom_errorbar(). They were supposed to display the standard deviation for each column


Solution

  • Is this what you had in mind? where the error bar represents plus and minus one standard deviation from the mean?

    library(dplyr)
    library(ggplot2)
    
    df1 <- data.frame(type=as.factor(c("tree","tree","tree","tree", "bush","bush","bush", "bush","flower", "flower", "flower", "flower")),
                  age=as.factor(c(5,1,5,1,5,1,5,1,5,1,5,1)),
                  size=c(11,3,16,5,2,0.5,3,0.4,1,0.2,0.9,0.15))
    
    df2 <- 
      df1 |> 
      group_by(type, age) |> 
      summarise(sd = sd(size),
                mean_size = mean(size), .groups = "drop") |> 
      mutate(sd_min = mean_size - sd,
             sd_max = mean_size + sd)
    
    ggplot(df2, aes(age, mean_size, fill = type))+
      geom_col(position = position_dodge())+
      geom_errorbar(aes(ymin = sd_min, ymax = sd_max), position = position_dodge())
    

    Created on 2023-06-29 with reprex v2.0.2