【问题标题】:How to put dates on x axis with ggplot?如何使用ggplot将日期放在x轴上?
【发布时间】:2021-04-08 21:25:58
【问题描述】:

让我们考虑数据:

library(quantmod)
library(ggplot2)
start <- as.Date("2013-01-01")
end <- as.Date("2016-10-01")
# Apple stock
getSymbols("AAPL", src = "yahoo", from = start, to = end)
apple <- AAPL$AAPL.Close

我想用 ggplot 绘制苹果变量,所以:

ggplot()+aes(x=1:length(apple), y = apple)+geom_line()

但是我不知道如何在 x 轴上放置日期而不是观察次数。日期存储在 AAPL 数据框中:

head(AAPL)
           AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted
2013-01-02  19.77929  19.82143 19.34393   19.60821   560518000      17.06525
2013-01-03  19.56714  19.63107 19.32143   19.36071   352965200      16.84985
2013-01-04  19.17750  19.23679 18.77964   18.82143   594333600      16.38050
2013-01-07  18.64286  18.90357 18.40000   18.71071   484156400      16.28414
2013-01-08  18.90036  18.99607 18.61607   18.76107   458707200      16.32798
2013-01-09  18.66071  18.75036 18.42822   18.46786   407604400      16.07279

但我不知道如何提取这些日期。你知道怎么做吗?

【问题讨论】:

  • 这不是一个最小的可重复验证示例:cf。 minimal reproducible example
  • 您能否解释一下为什么您认为我的问题不符合要求?我阅读了您发送的内容,但我不知道您所说的“最小可重现可验证示例”是什么意思
  • 我的评论不再是因为你之后修复/编辑了这个问题。反正你接受了答案并不重要。

标签: r date ggplot2


【解决方案1】:

在zoo 对象中,日期存储在自定义属性中,但这不适用于 ggplot。

class(apple)
[1] "xts" "zoo"

您实际上可以使用zoo::index 函数访问这些日期:

head(zoo::index(apple))
[1] "2013-01-02" "2013-01-03" "2013-01-04" "2013-01-07" "2013-01-08" "2013-01-09"

另一种方法是转换为数据框,将日期放入行名中,然后将这些行名转换为带有tibble::rownames_to_column的列:

library(dplyr)
library(tibble)
apple %>%
  as.data.frame() %>%
  rownames_to_column("Date") %>%
  mutate(Date = as.Date(Date)) %>%
ggplot(aes(x = Date, y = AAPL.Close)) +
  geom_line()

【讨论】:

    【解决方案2】:

    使用autoplot.zoo,如下所示。如果您想要调整后的关闭,请将 Cl 替换为 Ad。

    请参阅?autoplot.zoo 了解更多信息。

    library(ggplot2)
    library(quantmod)
    
    getSymbols("AAPL")
    autoplot(Cl(AAPL))
    

    可以自定义 X 轴,例如

    autoplot(Cl(AAPL)) + scale_x_date(date_labels = "%Y", breaks = "year")
    

    但没有它的默认值可能就足够了。

    这是使用默认值的输出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-05
      • 1970-01-01
      • 2021-06-14
      • 2021-01-27
      • 2020-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多