2016-08-16 78 views
0

我有類似下面的數據集:訂單保理時間序列數據

a <- read.table(header=TRUE, text="Time Counter Speed 
7:55:00 CT08W 63.79 
9:30:00 CT08W 67.69 
7:05:00 CT11W 68.34 
8:40:00 CT10W 68.39 
11:00:00 CT11W 68.00 
10:40:00 CT01W 21.57 
11:35:00 CT02W 72.03 
5:25:00 CT12W 66.93 
6:10:00 CT02W 62.79 
12:05:00 CT02W 71.79     ") 
a 
     Time Counter Speed 
1 7:55:00 CT08W 63.79 
2 9:30:00 CT08W 67.69 
3 7:05:00 CT11W 68.34 
4 8:40:00 CT10W 68.39 
5 11:00:00 CT11W 68.00 
6 10:40:00 CT01W 21.57 
7 11:35:00 CT02W 72.03 
8 5:25:00 CT12W 66.93 
9 6:10:00 CT02W 62.79 
10 12:05:00 CT02W 71.79 

str(a) 
'data.frame': 10 obs. of 3 variables: 
$ Time : Factor w/ 10 levels "10:40:00","11:00:00",..: 8 10 7 9 2 1 3 5 6 4 
$ Counter: Factor w/ 6 levels "CT01W","CT02W",..: 3 3 5 4 5 1 2 6 2 2 
$ Speed : num 63.8 67.7 68.3 68.4 68 ... 

我不想使用as.POSIXct的解決方案,因爲它涉及到的困難,而標註的身影。

ggplot(a, aes(x=Time, y=Counter, fill=Speed)) 

enter image description here

該圖顯示,時間被錯誤排序。是否有一種方法可以在考慮時間的情況下排序?

+0

首先,您需要將變量強制轉換爲日期/時間格式。目前它是因素,這意味着訂單是用'levels($ TIME_CNTR)'打印的。 –

+0

我提到我想避免使用日期/時間格式,因爲這個問題需要很多註解,這在日期/時間格式圖中很難處理。我正在考慮對時間戳進行僞命令。 –

回答

1

您可以使用您的時間變量的日期時間格式來訂購您的因子。

關鍵是使用日期時間變量進行排序,這可以通過多種方式完成。在這裏,我創建了一個日期時間變量,並在進行因子變量時對其進行分類。

a$dt = as.POSIXct(a$Time, format = "%H:%M:%S") 

a$Time2 = factor(format(a$dt, "%H:%M:%S"), levels = format(sort(a$dt), "%H:%M:%S")) 
a$Time2 
[1] 07:55:00 09:30:00 07:05:00 08:40:00 11:00:00 10:40:00 11:35:00 05:25:00 06:10:00 12:05:00 
Levels: 05:25:00 06:10:00 07:05:00 07:55:00 08:40:00 09:30:00 10:40:00 11:00:00 11:35:00 12:05:00 

ggplot(a, aes(x=Time2, y=Counter, fill=Speed)) 

enter image description here

如果使用這種方法和時間是不是唯一的,你需要添加uniquelevels說法。

1
a$Time <- factor(a$Time, levels = a$Time[order(as.POSIXct(a$Time, format = "%H:%M:%S"))]) 
ggplot(a, aes(x=Time, y=Counter, fill=Speed))