User Tools

Site Tools


label_x_axis_in_time_series_object

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

label_x_axis_in_time_series_object [2015/12/16 13:26] (current)
vincenzo created
Line 1: Line 1:
 +<code c>
 +# 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"​))
 +</​code>​
label_x_axis_in_time_series_object.txt ยท Last modified: 2015/12/16 13:26 by vincenzo