Reputation: 708
I'm working with tsoutliers
to plot the outliers from a time series, but I'm having trouble getting the dates in the x-axis of the plot to display as actual dates. Right now they are displayed as what looks to be some type of Julian date; 16816, 16816.2, etc. I've researched around and haven't found much on this, but I'm wondering if there is a way to use ggplot()
with a ts
object, because I know ggplot2
automatically handles dates very well.
Here is the code I'm working with, I just put some quick sample data in for the dataframe, the actual data is coming from a dynamic PowerBI dataframe:
library(forecast)
library(tsoutliers)
library(lubridate)
library(dplyr)
library(ggplot2)
ActualDemand <- c(1000, 250, 500, 3000)
STRING_DATE <- c("05/13/2017","05/06/2017", "5/20/2017", "05/27/2017")
dataset <- data.frame(ActualDemand, STRING_DATE)
#convert from string to date
dataset$STRING_DATE = lubridate::mdy(dataset$STRING_DATE)
dataRowCount <- nrow(dataset)
#find start date
startDate <- NULL
for (i in 1:dataRowCount) {
if (i == 1) {
startDate <- dataset[i, 2]
next
}
compareDate <- dataset[i,2]
if (compareDate < startDate) {
startDate <- compareDate
} else {
next
}
}
#transformed set
datasetSorted <- dataset[order(dataset$STRING_DATE),]
#build time series, run outlier detection
ts <- ts(datasetSorted$ActualDemand, frequency = 52, start = startDate)
series.outliers <- tso(ts)
plot(series.outliers)
Here is what the output looks like:
Upvotes: 0
Views: 356
Reputation: 1460
You can overwrite xaxis
values as:
plot(series.outliers,
args.x.axis = list(at = time(series.outliers$y), labels=datasetSorted$STRING_DATE) )
Upvotes: 1