3

I am wondering how I can change date format.

The code I am working on is following:

library(quantmod)
getSymbols("AAPL")
price_AAPL <- AAPL[,6]
plot(price_AAPL, main = "The price of AAPL")

This results

enter image description here

I want to alter date format from

"%m %d %Y"

as shown in the graphic to

"%b-%d-%Y"

So I tried following after searching some tips:

plot(price_AAPL, main = "The price of AAPL", xaxt="n")
axis.Date(1,
          at=seq(head(index(price_AAPL),1), 
                 tail(index(price_AAPL),1), length.out=5), 
          format="%b-%d-%Y", las=2)

But this doesn't help, and doesn't even show any labeling on x-axis. I suppose that I might did something wrong with "axis.Date()".

Can anybody help me?

Ronak Shah
  • 286,338
  • 16
  • 97
  • 143
Louis
  • 43
  • 5

1 Answers1

6

With xts, you can use major.format directly.

plot(price_AAPL, main = "The price of AAPL",major.format="%b-%d-%Y")

enter image description here

However, you should know that zoo plots are generally more flexible.

plot.zoo(price_AAPL, main = "The price of AAPL", xaxt="n", xlab="")
axis.Date(1,at=pretty(index(price_AAPL)),
            labels=format(pretty(index(price_AAPL)),format="%b-%d-%Y"),
            las=2, cex.axis=0.7)

enter image description here

Pierre Lapointe
  • 14,914
  • 2
  • 31
  • 52
  • Thank you so much. I will take a look at "plot.zoo" more detail. – Louis Dec 17 '15 at 09:28
  • 2
    The parameter `major.format` passed into `plot.xts()` doesn't format the dates on the x-axis. But the parameter `format.labels` does format the dates: `plot(price_AAPL, main="The price of AAPL", format.labels="%b-%d-%Y")` – algoquant Jul 26 '18 at 11:55