【问题标题】:R - Having some trouble with plotting using time dataR - 使用时间数据绘图时遇到一些问题
【发布时间】:2017-08-06 16:44:26
【问题描述】:

我目前正在尝试在 R 中编写预测算法,但在从 txt 文件中提取时间数据时遇到问题。

我目前有一个包含以下数据的测试文本文件

x
1 2010-01-01
2 2010-07-02
3 2010-08-03
4 2011-02-04
5 2011-11-05
6 2011-12-06
7 2012-06-07
8 2012-08-30
9 2013-04-16
10 2013-03-18
11 2014-02-22
12 2014-01-27
13 2015-12-15
14 2015-09-28
15 2016-05-04
16 2017-11-07
17 2017-09-22
18 2017-04-04

当我提取它并尝试使用以下代码对其进行绘制时:

library(forecast)
library(ggplot2)

Quantity <- c(read.table("....Path..../Quantity.txt"))
Time <- c(read.table("....Path..../Time.txt"))


x <- ts(as.Date(unlist(Time)))
y <- unlist(Quantity)


plot(x,y)

生成的图表正确显示了图表上的所有点,时间标签除外(它们是 14500、16000 和 17500)。标签应该显示文件中的日期,但在我看来,它可能将数据视为数学总和(并进行计算得出这些值)而不是日期。

我还有一个问题,时间数据不是按时间顺序绘制的,而是按文件中的顺序绘制的。

这是另一个文件中的数据仅供参考:

x
1 5
2 3
3 8
4 4
5 0
6 5
7 2
8 7
9 4
10 2
11 6
12 8
13 4
14 7
15 8
16 9
17 4
18 6

如何纠正这两个问题?

提前致谢。

【问题讨论】:

    标签: r


    【解决方案1】:

    这是众多可能的解决方案之一。
    希望对你有帮助。

    # A dataset with date and x values
    # Important: the format of date is "character"
    df <- structure(list(date = c("2010-01-01", "2010-07-02", "2010-08-03", 
    "2011-02-04", "2011-11-05", "2011-12-06", "2012-06-07", "2012-08-30", 
    "2013-04-16", "2013-03-18", "2014-02-22", "2014-01-27", "2015-12-15", 
    "2015-09-28", "2016-05-04", "2017-11-07", "2017-09-22", "2017-04-04"
    ), x = c(5L, 3L, 8L, 4L, 0L, 5L, 2L, 7L, 4L, 2L, 6L, 8L, 4L, 
    7L, 8L, 9L, 4L, 6L)), .Names = c("date", "x"), row.names = c(NA, 
    -18L), class = "data.frame")
    str(df)
    
    # Create a x vector with dates as rownames
    x <- as.matrix(df$x)
    rownames(x) <- df$date
    # Convert in a xts object
    library(xts)
    x <- as.xts(x)
    
    # Plot the xts object
    plot(x, grid.col="white")
    

    【讨论】:

      【解决方案2】:

      要回答您的ggplot 问题,使用上面 Marco 提供的数据框,您只需使用:

      ggplot(df, aes(x = date, y = x)) + geom_line(group = 1)
      

      由于您只有一组或一组点,您必须在geom_line 中使用group = 1 arg。

      我要指出的一件事是您的时间序列数据具有不规则的周期,您必须确保在时间序列对象中考虑到这一点。大多数时间序列包都有自己的专用函数来处理数据和绘图。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-06
        • 1970-01-01
        • 2018-10-23
        • 1970-01-01
        • 1970-01-01
        • 2011-12-17
        相关资源
        最近更新 更多