Directly Plotting ts object with ggplot2

Try this:

library(zoo)
library(ggplot2)
library(scales)

autoplot(as.zoo(dat), geom = "point")

or maybe:

autoplot(as.zoo(dat), geom = "point") + scale_x_yearqtr()

See ?autoplot.zoo for more info.

Note: The code in the question works if you issue the command library(zoo) first.

Updates Added second solution, library(scales) and switched from yearmon to yearqtr.


Don't know why it worked before (since it would not seem to be valid under my understanding of Date functins) but you can fix it with the use of zoo::as.yearqtr

library(zoo)
?as.yearqtr
set.seed(12345)
dat <- ts(data=runif(n=10, min=50, max=100), frequency = 4, start = c(1959, 2))
df <- data.frame(date=as.Date(as.yearqtr(time(dat))), Y=as.matrix(dat))
library(ggplot2)
ggplot(data=df, mapping=aes(x=date, y=Y))+geom_point()
# No errors. The plot has YYYY-MM labeling as expected for a ggplot2-Date axis.

Tags:

R

Ggplot2