Search code examples
rggplot2line

How to create a reaction norm (joining means by line) in ggplot2 R?


I have the following data, where I want to plot "values" for species 1 and 2 across two time points (t1, t2). I want to create a plot where the raw values of each species is visible using geom_points (different colors). Also, I want to display the mean using a larger size of the same color. For a given species, I want to connect the mean at t1 and t2 (also called reaction norms). So in this example, the line for species 1 should slope upward, and that of species 2 should remain unchanged.

I have attempted the basic ggplot2 but I do not know how to add the lines and display the mean in larger size. Also, for some reason "fill" is not generating different colours.

time <- c("t1","t1","t1","t1","t1","t1","t2","t2","t2","t2","t2","t2")
species <- c(1,1,1,2,2,2,1,1,1,2,2,2)
value <- c(1,2,3,11,12,13,4,5,6,11,12,13)

df <- data.frame(time, species,value)
df$time <- as.factor(df$time)
df$species <- as.factor(df$species)

ggplot(df,aes(x=time, y=value, fill = species)) + 
  theme_bw() + 
  geom_point() + 
  stat_summary(fun.y=mean, position = "dodge") + 
  stat_summary(geom="errorbar", fun.data= mean_cl_boot, width = 0.1, size = 0.2, col = "grey57") + 
  ylab("Fitness") 

Solution

  • Something like

    ggplot(df,aes(x=time, y=value, color = species)) + # Change fill to color
      theme_bw() + 
      geom_point() + 
      stat_summary(fun.y=mean, position = "dodge") + 
      stat_summary(
        geom="errorbar", 
        fun.data= mean_cl_boot, 
        width = 0.1, size = 0.2, col = "grey57") + 
      # Lines by species using grouping
      stat_summary(aes(group = species), geom = "line", fun.y = mean) +
      ylab("Fitness")
    

    If you want two errorbars you can add the group of the line summary into the ggplot aesthetics.