Home > OS >  R TimeSeries Plotting for Weekly Data
R TimeSeries Plotting for Weekly Data

Time:11-27

I have weekly data starting from week 2 in the year 2015 till week 9 in 2016, after fitting and plotting my forecast, The x-axis doesn't make sense. How can I share x-axis values in terms of months/week#. Thank you

Current Forecast Plot

TS1<-ts(DUMMYDATA,frequency =52,start = c(2015,02),end = c(2016,09))

I tried creating my own x-axis but I am not able to reflect it correctly in terms of Time components

CodePudding user response:

First I generated some random reproducible data. You could directly generate dates in your ts with as.Date. After that you need to convert the time series to a date format. To show the axis with month/weeks dates, you can use scale_x_date with date_labels form week and month. Here is a reproducible example:

library(ggplot2)
# Generate random reproducible data
set.seed(1)
DUMMYDATA <- cumsum(rnorm(10000))
TS1<-ts(DUMMYDATA, frequency = 52, start = as.Date('2015-02-01'), end = as.Date('2016-09-01'))

# Convert to dataframe
data = data.frame(y=as.matrix(TS1), date=time(TS1))

# convert date to date format
data$date <- as.Date(as.numeric(time(data$date)), origin = "1970-01-01")

ggplot(data, aes(x = date, y = y))  
  geom_line()  
  scale_x_date(date_labels = "%b-%W", 
               date_breaks = '1 week')  
  guides(x = guide_axis(angle = 90))  
  theme_bw()

Created on 2022-11-27 with reprex v2.0.2

If you don't want to show each week, you can change date_breaks to months like this:

library(ggplot2)
ggplot(data, aes(x = date, y = y))  
  geom_line()  
  scale_x_date(date_labels = "%b-%W", 
               date_breaks = '1 month')  
  guides(x = guide_axis(angle = 90))  
  theme_bw()

Created on 2022-11-27 with reprex v2.0.2

CodePudding user response:

One way to do this is to use a tsibble object rather than a ts object. Here is an example:

library(ggplot2)
library(tsibble)
library(lubridate)
library(feasts)

set.seed(1)
df <- tsibble(
  Week = yearweek(seq(as.Date("2015-01-01"), length=300, by="7 days")),
  TS1 = cumsum(rnorm(300))
)
#> Using `Week` as index variable.
df |> autoplot(TS1)  
  scale_x_yearweek(date_breaks = '1 year')

Created on 2022-11-27 with reprex v2.0.2

It appears that you are using the forecast package to create forecasts from ts objects. The equivalent functionality is provided in the fable package to create forecasts from tsibble objects. See my book for lots of examples, including using weekly data.

  • Related