Label X Axis in Time Series Plot using R

后端 未结 5 1596
無奈伤痛
無奈伤痛 2020-12-01 07:02

I am somewhat new to R and have limited experience with plotting in general. I have been able to work get my data as a time series object in R using zoo, but I am having a

5条回答
  •  一个人的身影
    2020-12-01 07:33

    I have captured all the above and a couple of extra options in one place, for my own reference:

    # Time series plots with good X axis labels
    library(zoo)
    # data
    today = Sys.Date()
    dates = as.Date((today-500):today)
    z = zoo (100+cumsum(rnorm(501)), dates)
    
    # method1 : default X axis labels do not look good
    ?plot.zoo
    plot(z)
    ?plot.ts
    plot(ts(z))
    
    # method 2 : Lattice
    library(lattice)
    ?xyplot.zoo
    xyplot(z)
    xyplot(z, lwd=2, col="tomato")
    
    # method 3 : XTS
    library(xts)
    ?plot.xts
    plot(as.xts(z))
    plot(as.xts(z), auto.grid=F, major.format="%b %y", las=2)
    
    # method 4 : Base graph
    timeline = time(z)
    summary(timeline)
    index = seq(from=1, to=length(timeline), 90) # put ticks every 90 days
    plot(z, xaxt="n")
    axis(side=1, at=timeline[index], label=format(timeline[index], "%b %y"), cex.axis=0.8)
    
    # method 5 : ggplot
    library(ggplot2)
    library(scales)
    ?date_breaks
    df = data.frame(date=as.POSIXct(time(z)), value=as.numeric(z))
    head(df)
    # default plot
    ggplot(df, aes(x=date, y=value)) + geom_line()
    # formatted
    ggplot(df, aes(x=date, y=value)) + geom_line() + 
       scale_x_datetime(labels=date_format("%b '%y"))
    # custom breaks
    ggplot(df, aes(x=date, y=value)) + geom_line() + 
       scale_x_datetime(labels=date_format("%b '%y"), breaks=date_breaks("3 months"))
    

提交回复
热议问题