0
> str(env)
tibble [1,363 × 15] (S3: tbl_df/tbl/data.frame)
 $ use_for_analysis: chr [1:1363] "Standard" "Standard" "Standard" "Standard" ...
 $ Date            : POSIXct[1:1363], format: "2011-01-07" "2011-01-07" "2011-01-07" ...
 $ CYR             : Factor w/ 18 levels "2005","2006",..: 7 7 7 5 7 7 7 7 7 5 ...
 $ Season          : Factor w/ 2 levels "DRY","WET": 1 1 1 1 1 1 1 1 1 1 ...
 $ Month           : num [1:1363] 1 1 1 1 1 1 1 1 1 1 ...
 $ Time            : POSIXct[1:1363], format: "1899-12-31 10:05:00" "1899-12-31 10:38:00" "1899-12-31 10:55:00" ...
 $ time2           : POSIXct[1:1363], format: "2022-12-01 10:05:00" "2022-12-01 10:38:00" "2022-12-01 10:55:00" ...
 $ DT              : POSIXct[1:1363], format: "2011-01-07 10:05:00" "2011-01-07 10:38:00" "2011-01-07 10:55:00" ...
 $ Site            : Factor w/ 47 levels "1","2","3","4",..: 46 44 43 22 45 47 42 33 34 19 ...
 $ temp            : num [1:1363] 17.6 18.4 18.6 18.8 18.8 ...
 $ sal             : num [1:1363] 31.2 30.3 29.9 18.5 31.3 ...
 $ DO              : num [1:1363] 6.12 6.65 6.29 6.56 7.25 ...
 $ water_depth     : num [1:1363] 39 42 58 36 58 70 68 71 40 67 ...
 $ sed_depth       : num [1:1363] 31 143 89 28 111 31 123 29 42 2 ...
 $ Month2          : Factor w/ 8 levels "Jan","Feb","Mar",..: 1 1 1 1 1 1 1 1 1 1 ...

ggplot(env, aes(x=time2, y=temp, color = Month2)) + 
  geom_point(alpha = 0.2) + 
  geom_smooth(method='gam', formula = y ~ splines::ns(x,2) + b, se=FALSE) + # y=temp, x=time2, b=Month2, no?
  facet_wrap(~CYR)

How would I add a GAM spline to each group (Month2)? This method doesn't seem to work for me. Is the formula within the 'geom_smooth' wrong?

enter image description here

stefan
  • 90,330
  • 6
  • 25
  • 51
Nate
  • 411
  • 2
  • 10
  • 1
    Why don't you want to use penalised splines with `gam()`, which is the default? I would have expected `+ geom_smooth(method='gam', se = FALSE)` to do exactly what you wanted with a penalised spline, rather than forcing a 2df natural spline. FWIW, you'd get the same fit more efficiently using your `formula` but with `method = "lm"`. – Gavin Simpson Dec 02 '22 at 08:27
  • Oh ok, I actually wasn't aware of that function. I thought one had to choose the (power?) before-hand. Thank you for the advice! – Nate Dec 02 '22 at 14:32

1 Answers1

0

Got it (didn't need the "+b"):

ggplot(env, aes(x=time2, y=temp, group = Month2, color = Month2)) + 
      geom_point(alpha = 0.2) + 
      geom_smooth(method='gam', formula = y ~ splines::ns(x,2), se=FALSE) +
      facet_wrap(~CYR)
Nate
  • 411
  • 2
  • 10