2017-08-06 50 views
0

我目前正在尝试在R中编写预测算法,但我遇到了从txt文件中提取我的时间数据的问题。R - 在使用时间数据绘图时遇到一些麻烦

我目前有下列数据的测试文本文件

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 

我怎样才能纠正这些2个问题?

在此先感谢。

回答

2

这是许多可能的解决方案之一。
我希望它能帮助你。

# 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") 

enter image description here

1

enter image description here要回答你的ggplot问题,使用数据帧马尔科上面提供,您只需使用:

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

因为你只有一组或一组点,您必须使用geom_line中的group = 1参数。

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

相关问题