Home > other >  Apply geom_smooth to GAM by group?
Apply geom_smooth to GAM by group?

Time:12-08

> 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)? enter image description here

CodePudding user response:

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)
  • Related