Trying to figure out how to plot an age-length line / scatter graph in ggplot2?

Please ask your questions with a reproducible example like this one

df <- data.frame(
    year = c(2017L, 2017L, 2017L, 2017L, 2017L, 2017L, 2017L, 2017L,
             2017L, 2017L, 2017L, 2017L, 2017L, 2017L, 2017L, 2017L,
             2017L),
    total_length = c(68, 35, 37, 36, 37.5, 41, 36, 51, 49, 68, 54, 53, 49, 51,
                     50, 59, 55),
    age = c(4, 1, 1, 1, 1, 2, 2, 2, 2, 4, 3, 3, 3, 3, 4, 4, 3)
)

library(ggplot2)
library(dplyr)
df %>% 
    group_by(age) %>% 
    mutate(mean_length = mean(total_length)) %>% 
    ggplot(aes(x = age, y = total_length)) +
    geom_point(color = "blue", shape = 1) +
    geom_smooth(aes(y = mean_length), method = "loess") +
    geom_point(aes(y = mean_length), color = "red")

Created on 2019-02-21 by the reprex package (v0.2.1)

If you've never heard of a reprex before, you might want to start by reading this FAQ:

2 Likes