Draw a ts object directly with ggplot2

It is interesting if there is a function for constructing the ts object directly ggplot2. I used to use the following strategy, but now it throws 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 build a ts object with ggplot2 .

+10
source share
3 answers

Try the following:

 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 .

Note. . By the way, the code in the question works if you first run the library(zoo) command.

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

+8
source

I don’t know why this worked earlier (since it would not seem valid in my understanding of Date functionals), but you can fix it with 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. 
+5
source

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 
+2
source

Source: https://habr.com/ru/post/976641/


All Articles