alathrop
12/5/2017 - 4:17 PM

ggplot time series, facet, loess, and date

filter on dates facet by factor levels, facet_grid, facet_wrap overlay dates with vertical red lines loess smoothing add labels

# from Lubrizol NOV 2017
# written by Andy L

# P12 2016 Priority 0 fails
# ~~~~~~~~~~~~~~~~~~~~~~~~~
p_E12_2016 <- viz_df %>%
  
  filter(
    
    time_stamp_h > ymd("2016-01-01") & time_stamp_h < ymd("2016-12-31"),

    !measure %in% c(
      #"Process Flow", 
      "Process Temp",
      #"Pump Speed",
      "Process Pressure"
      #"Pump Speed"
      #"Pump")
    )
  )%>% 
  
  ggplot() +
  geom_line(aes(x = time_stamp_h, y = value)) +
  facet_grid(measure ~ functional_location, scales = "free") +
  
  # vertical red line for failures
  geom_vline(xintercept = as.numeric(as.POSIXct("2016-01-22 12:00:00")),  color = "red", size =  1.3) +
  geom_vline(xintercept = as.numeric(as.POSIXct("2016-05-06 12:00:00")),  color = "red",  size = 1.3) +
  geom_vline(xintercept = as.numeric(as.POSIXct("2016-10-10 12:00:00")),  color = "red",  size = 1.3)
  
  # ~~~~~~~~~~~
  # example with loess smoothing
  # ~~~~~~~~~~~
  
  # 2016 Fail 1 short
# ~~~~~~~~~~~~~~~~~
pre_days <- 10
post_days <- 5
f_date <-  ymd_hms("2016-10-10 12:00:00")
f_min <- f_date - days(pre_days)
f_max <- f_date + days(post_days)

p_E12_f1_2016s <- viz_df %>%
  
  filter(
    
    time_stamp_h > f_min & time_stamp_h < f_max,
    
    !measure %in% c(
      #"Process Flow", 
      "Process Temp",
      "Process Pressure"
      #"Process Flow",
      #"Pump Speed"
      #"Pump Speed"
    )
    
  ) %>% 
  
  ggplot(aes(x = time_stamp_h, y = value)) +
  geom_line() +
  
  # loess line - NOTE: aes must be in ggplot() NOT in geom_line()
  geom_smooth(span = 0.15) +
  
  facet_grid(measure ~ functional_location, scales = "free") +
  
  # vertical red line for failures
  geom_vline(xintercept = as.numeric(as.POSIXct("2016-01-22 12:00:00")),  color = "red", size =  1.3) +
  geom_vline(xintercept = as.numeric(as.POSIXct("2016-05-06 12:00:00")),  color = "red",  size = 1.3) +
  geom_vline(xintercept = as.numeric(as.POSIXct("2016-10-10 12:00:00")),  color = "red",  size = 1.3)
  
  # use facet_wrap
  # facet by lines
ggplot(data = repairs, aes(x = ttf)) +
  theme_bw() +
  geom_histogram(stat = "bin", bins = 40, aes(fill = line)) +
  facet_wrap(~ line, nrow = 2) + 
  labs(
    title = "Distribution of time to failure", 
    x = "time to failure",
    y = "# of failures" )