2017-08-06 51 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參數。

我會指出的一件事是,你的時間序列數據有不規則的週期,你必須確保你在你的時間序列對象中考慮到這一點。大多數時間序列軟件包都有自己專門的功能來處理數據和繪圖。

相關問題