Yang Yang
Yang Yang

Reputation: 902

How to set my own x axis labels for a time series plot in R?

I have a time series and when I plot it, the default x-axis is not well labeled.

aa=sample(x=1:500,size = 804,replace = T)
Year_mon <- seq(from=as.Date("1950-01-15"),to=as.Date("2016-12-15"),by="months")
plot(aa~Year_mon, type="l", lty=1)

enter image description here

What I want is to show 1950, 1960, 1970,..., 2010 as the x axis label. I have tried the following codes, but failed. Is there any suggestion? Thanks a lot.

plot(aa~Year_mon, type="l", lty=1,xaxt="n")
ix <- seq(1, 721, by=120)
axis(side=1, at=ix, labels=seq(1950,2010,by=10))

enter image description here

Upvotes: 1

Views: 318

Answers (1)

www
www

Reputation: 39154

We can use axis.Date to achieve this.

set.seed(1234)
aa <- sample(x=1:500,size = 804, replace = T)
Year_mon <- seq(from = as.Date("1950-01-15"), to = as.Date("2016-12-15"), by = "months")
plot(aa~Year_mon, type = "l", lty = 1)
axis.Date(1, at = as.Date(paste0(seq(1950, 2010, 10), "-01-01")), format="%Y")

enter image description here

Upvotes: 2

Related Questions