regression line with geom_smooth for groups and coefficient estimate labels

Thans for that! Note that below is a reprex, the ideal format for seeking help here on coding forums..

cats <- structure(list(
  life_years = c(33, 42, 21, 11, 11, 11, 32, 32,32, 44, 44, 49), 
  happy_years = c(11, 33, 14, 4, 4, 2, 23, 12,11, 23, 33, 22), 
  cat_type = c("orange", "orange", "black", "white","white", "white", "black", "orange", "white", "black", "black","white")), 
  class = c("tbl_df", "tbl", "data.frame"), 
  row.names = c(NA, -12L))

ggplot(data = cats, aes(x = life_years, y =happy_years, group = cat_type, color = cat_type)) +
  facet_wrap(~ cat_type) +
  geom_point() +
  geom_smooth(method = lm)
#> `geom_smooth()` using formula = 'y ~ x'

Created on 2022-12-22 with reprex v2.0.2

The regression line for each panel appears different to me.

additionally, is it possible to label the coefficient of each line (like if its .34, or .55) etc thank you

You can add arbitrary annotations via annotate. Create an annotation layer — annotate • ggplot2. I'm actually not sure the best way to add specifically the labels of each coefficient though.

Winston Chang's R Graphics Cookbook (which I've found useful for ten years now!) has some guidance, 5.9 Adding Annotations with Model Coefficients | R Graphics Cookbook, 2nd edition. But I do feel there has got to be a helper package that makes this trivially easy -- sorry I just don't know it.

1 Like