Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directly Plotting ts object with ggplot2

Tags:

r

ggplot2

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.

like image 654
MYaseen208 Avatar asked Oct 12 '14 17:10

MYaseen208


3 Answers

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.

like image 89
G. Grothendieck Avatar answered Sep 21 '22 21:09

G. Grothendieck


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.
like image 22
IRTFM Avatar answered Sep 18 '22 21:09

IRTFM


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
like image 20
Rafael Díaz Avatar answered Sep 21 '22 21:09

Rafael Díaz