twitter / AnomalyDetection

Anomaly Detection with R
GNU General Public License v3.0
3.55k stars 779 forks source link

POSIXct and POSIXlt problem with the simple example #101

Open SherryPan123 opened 6 years ago

SherryPan123 commented 6 years ago

After installing dependency and the project, I follow the simple example in README:

data(raw_data)
res = AnomalyDetectionTs(raw_data, max_anoms=0.02, direction='both', plot=TRUE)
res$plot

When I run res$plot, an error occurs: Error: Columnxis a date/time and must be stored as POSIXct, not POSIXlt Does anyone know how to solve the problem? Thx

supermdat commented 6 years ago

I encountered something similar, and I believe the issue results from the latest update (effective 2018-07-03) of ggplot2 to version 3.0.0. Apparently, AnomalyDetection will internally convert to posixlt (see https://github.com/twitter/AnomalyDetection/issues/29 comment on 2015-04-02), which ggplot2 doesn't work with in the latest version.

My short-term solution was to simply revert back to ggplot2 version 2.2.1 require(devtools) install_version("ggplot2", version = "2.2.1", repos = "http://cran.us.r-project.org")

An internal fix for posixlt conversion would be ideal. But as you saw, this only affects the plotting capability of AnomalyDetection. So if you wanted to use the latest ggplot2 version, you could also build the plot yourself.

xvanausloos commented 6 years ago

Thanks a lot: this fix works perfect for me.

baztastic commented 6 years ago

To expand on @supermdat 's answer, to work around this without downgrading ggplot2, use something like this:

data(raw_data)
raw_data$timestamp <- as.POSIXct(raw_data$timestamp)
res <- AnomalyDetectionTs(raw_data, max_anoms=0.02, direction='both', plot=FALSE)
res$anoms$timestamp <- as.POSIXct(res$anoms$timestamp)
ggplot(raw_data, aes(timestamp, count)) + 
  geom_line(data=raw_data, aes(timestamp, count), color='blue') + 
  geom_point(data=res$anoms, aes(timestamp, anoms), color='red')

Edit: After writing this up, I found the more up-to-date fork of this package, that has solved a bunch of problems: https://github.com/hrbrmstr/AnomalyDetection