Skip to content

Instantly share code, notes, and snippets.

@jwaage
Created September 15, 2017 08:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwaage/4aa99783352100654980d20c93fae27e to your computer and use it in GitHub Desktop.
Save jwaage/4aa99783352100654980d20c93fae27e to your computer and use it in GitHub Desktop.
Sine curve function and plot
# Season test
# Do a sine function with arbitrary phase shift and plot the results with confidence band.
library(tidyverse)
library(broom)
set.seed(1)
x <- runif(200, 1, 365) %>% round(0)
y <- sin(2*pi*x/365) + rnorm(200, 0, 0.5)
yshift <- sin(2*pi*x/365 - 0.3*pi) + rnorm(200, 0, 0.5)
df <- data.frame(x, y, yshift)
ggplot(df, aes(x, y)) + geom_point()
ggplot(df, aes(x, y)) + geom_point() + geom_smooth()
ggplot(df, aes(x, y)) + geom_point() + geom_smooth(method = "lm")
ggplot(df, aes(x, yshift)) + geom_point() + geom_smooth(method = "lm")
lm(y ~ x, data = df) %>% summary
lm(yshift ~ x, data = df) %>% summary
mod1 <- lm(y ~ cos(2*pi*x/365), data = df)
summary(mod1)
bind_cols(df, mod1 %>% augment) %>%
ggplot(aes(x, y)) + geom_point() + geom_line(mapping = aes(y = .fitted), col = "red")
mod1 <- lm(yshift ~ cos(2*pi*x/365) + sin(2*pi*x/365), data = df)
summary(mod1)
bind_cols(df, mod1 %>% augment) %>%
ggplot(aes(x, yshift)) + geom_point() + geom_ribbon(aes(ymin = .fitted - 1.96*.se.fit, ymax = .fitted + 1.96*.se.fit), alpha = 0.5) + geom_line(mapping = aes(y = .fitted), col = "red")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment