R plot for RSiteCatalyst Anomaly Detection

  • Download Gist
rsitecatalyst-anomaly-detection-plot.R
R
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
#Plot data using ggplot2
library(ggplot2)
 
#Combine year/month/day together into POSIX
pageviews_w_forecast$date <- ISOdate(pageviews_w_forecast$year, pageviews_w_forecast$month, pageviews_w_forecast$day)
 
#Convert columns to numeric
pageviews_w_forecast$pageviews <- as.numeric(pageviews_w_forecast$pageviews)
pageviews_w_forecast$pageviews_upper <- as.numeric(pageviews_w_forecast$pageviews_upper)
pageviews_w_forecast$pageviews_lower <- as.numeric(pageviews_w_forecast$pageviews_lower)
 
#Calculate points crossing UCL or LCL
pageviews_w_forecast$outliers <-
ifelse(pageviews_w_forecast$pageviews > pageviews_w_forecast$pageviews_upper, pageviews_w_forecast$pageviews,
ifelse(pageviews_w_forecast$pageviews < pageviews_w_forecast$pageviews_lower, pageviews_w_forecast$pageviews, NA))
 
#Add LCL and UCL labels
LCL <- vector(mode = "character", nrow(pageviews_w_forecast))
LCL[nrow(pageviews_w_forecast)] <- "LCL"
UCL <- vector(mode = "character", nrow(pageviews_w_forecast))
UCL[nrow(pageviews_w_forecast)] <- "UCL"
pageviews_w_forecast <- cbind(pageviews_w_forecast, LCL)
pageviews_w_forecast <- cbind(pageviews_w_forecast, UCL)
 
#Create ggplot with actual, UCL, LCL, outliers
ggplot(pageviews_w_forecast, aes(date)) +
theme_bw(base_family="Garamond") +
theme(text = element_text(size=20)) +
ggtitle("Page Views for randyzwitch.com\n") +
geom_line(aes(y = pageviews), colour = "grey40") +
geom_point(aes(y = pageviews), colour = "grey40", size=3) +
geom_point(aes(y = outliers), colour = "red", size=3) +
geom_line(aes(y = pageviews_upper), colour = "green4", linetype = "dashed") +
geom_line(aes(y = pageviews_lower), colour = "green4", linetype = "dashed") +
xlab("\nDate\n\nNote: Upper and Lower Control Limits calculated by Adobe Analytics API") +
ylab("Page Views\n") +
geom_text(aes(label=UCL, family = "Garamond"), y = pageviews_w_forecast$pageviews_upper, size=4.5, hjust = -.1) +
geom_text(aes(label=LCL, family = "Garamond"), y = pageviews_w_forecast$pageviews_lower, size=4.5, hjust = -.1)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.