2015-10-14 96 views
0

我是R的新手,從這個簡單的問題出發。我想繪製包含時間值的輸入文件的值。輸出圖像應該包含藍線(對於Dist爲09.0的行)和紅線(對於Dist爲04.0的行)。從R中的文件繪製時間值的最簡單方法是什麼?

我設法生成輸入整數值直接進入graph.r的圖形,但現在我想graph.rinput.txt獲取這些值來代替,並讓他們格式化爲時間(h:mm:ss的)。這是可能的,還是我必須解析input.txt之前餵它到R?


input.txt中

Date(x) Dist Time(y) 
120926 09.0 1:54:42 
121001 04.0 0:19:00 
121202 04.0 0:18:53 
121206 09.0 1:13:19 

graph.r

#!/usr/bin/env Rscript 

# Define the cars vector with 5 values 
input <- 'path/to/input.txt' 
nine <- file(input)    #how to parse it? 
four <- c(3600, 12:00, 16, 4, 9) #this fails because of "12:00" 

# Set output file type to png 
png("output.png", width=320, height=240) 

# Graph using blue points for Dist 9, and red for Dist 4. 
plot(nine, type="o", col="blue") 
plot(four, type="o", col="red") 

# Output to file 
dev.off() 

素描期望的結果,減xy標籤和圖例

sketch

回答

0

這是怎麼了我會去 關於它。您將需要「as.POSIXct」的圖形包,並且一旦定位線被執行,您將需要單擊位於圖例頂角的位置的圖。

data=read.table("input.txt",head=T) 

library(graphics) 
plot(data$Date.x.,as.POSIXct(strptime(data$Time.y.,format="%H:%M:%S")),type="n", xlab="Date",ylab="Time") 
lines(data$Date.x.[data$Dist==4],as.POSIXct(strptime(data$Time.y.,format="%H:%M:%S"))[data$Dist==4],col="red") 
lines(data$Date.x.[data$Dist==9],as.POSIXct(strptime(data$Time.y.,format="%H:%M:%S"))[data$Dist==9],col="blue") 

leg=locator(1) 
legend(leg,legend=c(4,9),col=c("red","blue"),lty=1) 
+0

我不知道我很理解你的第二句話。爲什麼點擊?是否不可能以非交互方式執行此操作? – octosquidopus

+0

是的,你不需要使用locator()函數爲你的圖例選擇點,但是你需要手動提供x和y值。 –

+0

如果這對你有用,你能接受答案嗎? –

相關問題