R - How can I change date format when I plot an xts & zoo object?

大兔子大兔子 提交于 2019-12-02 02:12:35

问题


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

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?


回答1:


With xts, you can use major.format directly.

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

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)



来源:https://stackoverflow.com/questions/34319504/r-how-can-i-change-date-format-when-i-plot-an-xts-zoo-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!