Reputation: 23898
I wonder if there is a function to plot ts
object directly with ggplot2. In past, I was using the following strategy but now it is throwing an error.
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(time(dat)), Y=as.matrix(dat))
library(ggplot2)
ggplot(data=df, mapping=aes(x=date, y=Y))+geom_point()
Error
Error in as.Date.default(time(dat)) :
do not know how to convert 'time(dat)' to class “Date”
How can I directly plot ts
object with ggplot2
.
Upvotes: 13
Views: 11765
Reputation: 269704
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
.
Upvotes: 11
Reputation: 2289
This code works for me
set.seed(12345)
dat <- ts(data=runif(n=10, min=50, max=100), frequency = 4, start = c(1959, 2))
library(ggfortify)
autoplot(dat, geom = "point", ts.colour = ('dodgerblue3')) #Option 1
library(zoo)
autoplot.zoo(as.zoo(dat), geom = "point") #Option 2
Upvotes: 3
Reputation: 263382
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.
Upvotes: 5