简体   繁体   中英

R: How do you put the month - year on the X axis of a plot.zoo multiple plot?

In a shiny app I would like to put the month - year (ie "Jan- 13", "Feb- 13") of a plot.zoo multiple line plot. I have googled and it looks like you have to use a panel and if statement to find the last plot but I still cannot get the month - year to show up on the x axis.

Here is code you can run:

library("zoo")

Factors <- matrix(seq(from=1, to=9, by=1), nrow=3,ncol=3)
Factors
datesNumeric <- cbind(20130101, 20130220,20130801)
dates <- as.Date(as.character(datesNumeric), format="%Y%m%d")
ticks <- seq(dates[1], dates[length(dates)], by = "1 month") #I make some ticks
ticks

my.panel <- function(x, y, ..., pf = parent.frame()) {
  grid(NA,NULL)
  #abline(v=seq(1,168,24),col = "lightgray", lty = "dotted", lwd = par("lwd"))
  lines(x, y, ...)

  #if bottom panel
  if (with(pf, length(panel.number) == 0 ||panel.number %% nr == 0 || panel.number == nser)) {
    #axis(1, at = ticks, labels = ticks)
    axis.Date(1, at = ticks, format= "%m-%y", las = 1)
  }
 }

plot(as.zoo(Factors), main="Factors 1,2, & 3", ylab=c("Factor 1","Factor 2","Factor 3") ,      xlab= "Date", panel = my.panel,yax.flip=FALSE,col=1:3,xaxt="n")

Any idea how to get dates (ie "Jan- 13", "Feb- 13", etc...) to show up on the x axis? thank you.

You should create a reproducible example. plot.zoo is just a base plot. So to format axis with dates you should use axis.Date .

x.Date <- as.Date(paste(2003,  c(1, 3, 7, 9, 14), 02,sep = "-"))
x <- zoo(rnorm(5), x.Date)
plot(x,xaxt="n")
axis.Date(1, at = x.Date, format= "%m-%y", las = 1)

在此处输入图片说明

EDIT after op update:

You should create a valid zoo object.

 plot(zoo(x=Factors,order.by=ticks),  ## here your error
     main="Factors 1,2, & 3", ylab=c("Factor 1","Factor 2","Factor 3") ,    
 xlab= "Date", panel = my.panel,yax.flip=FALSE,col=1:3,
     format='%b-%y') ## format labels 

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM