【问题标题】:R - How can I change date format when I plot an xts & zoo object?R - 绘制 xts 和 zoo 对象时如何更改日期格式?
【发布时间】:2015-12-16 18:29:46
【问题描述】:

我想知道如何更改日期格式。

我正在处理的代码如下:

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

这个结果

我想更改日期格式

"%m %d %Y"

如图所示

"%b-%d-%Y"

所以我在搜索了一些提示后尝试了以下操作:

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)

但这无济于事,甚至没有在 x 轴上显示任何标签。我想我可能对“axis.Date()”做错了。

谁能帮帮我?

【问题讨论】:

    标签: r plot xts quantmod as.date


    【解决方案1】:

    使用xts,可以直接使用major.format

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

    但是,您应该知道zoo 绘图通常更灵活。

    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)
    

    【讨论】:

    • 非常感谢。我会更详细地看一下“plot.zoo”。
    • 传递给plot.xts() 的参数major.format 不会格式化x 轴上的日期。但参数format.labels 确实格式化了日期:plot(price_AAPL, main="The price of AAPL", format.labels="%b-%d-%Y")
    猜你喜欢
    • 2018-06-08
    • 1970-01-01
    • 2011-03-14
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 2020-10-28
    相关资源
    最近更新 更多