r.user.05apr
r.user.05apr

Reputation: 5456

Format x-axis of time series plot as date

How can I add dates to the x-axis instead of decimal numbers?

dates<-seq(from=as.Date("2000/7/1"), by="month", length.out=18)
y<-rnorm(18,20,3)
myts<-ts(data=y,
         start=c(as.numeric(format(min(dates),"%Y")),
                 as.numeric(format(min(dates),"%m"))),
         frequency=12,
         deltat=1/12)
plot(myts,ylab='Y',xlab='Date',type='l')

Thanks&kind regards

Upvotes: 1

Views: 3233

Answers (2)

d.b
d.b

Reputation: 32538

Maybe just plot without converting to time series, suppress x-axis labels with xaxt = "n" when plotting, and then add x-axis labels later with axis.

dates_label = as.character(dates)
plot(x = dates, y, las = 2, xaxt = "n", xlab = "", type = "l")
axis(1, at = dates, labels = dates_label, las = 2, cex.axis = .85)

enter image description here

Upvotes: 1

StatLearner
StatLearner

Reputation: 159

Probably the easiest way to format x axis is plotting with ggplot:

library(ggplot2)
mytsDF <- data.frame(data = myts, date = dates)
ggplot(mytsDF, aes(date, data)) + geom_line() +
  scale_x_date(date_labels = "%d-%m-%Y", date_breaks = "3 months") + 
  xlab("") + ylab("y") + ggtitle("Time Series Plot")

enter image description here

Upvotes: 0

Related Questions