2017-07-18 20 views
0

我有一個數據庫與日期(數據$時間)和數值(數據$ ert)的變量。我是R新手,想要學習(在這裏檢查了很多鏈接,在Google上;也使用了?geom_rect),可能這是一個愚蠢的問題。如何在使用日期變量作爲x軸時使用geom_rect [R]?

library(ggplot2) 
    data<-read.csv("pt1.csv", header=T, sep="\t", dec=",") 
    data$time<-as.Date(data$time, "%d/%m/%y", origin="1970-01-01") 
    pt1.plot<-<-ggplot(data, aes(time, ert, group=1, na.rm=T))+geom_rect(aes(xmin=2, xmax=Inf, ymin=-Inf, ymax=Inf), fill="lightgreen", alpha=0.03)+geom_line()+labs(x="", y="ert")+geom_hline(aes(yintercept=0.5), colour="#990000", linetype="dashed") 
    pt1.plot 

當試圖想象它給了我這個錯誤的情節:

Error in as.Date.numeric(value) : 'origin' must be supplied 

我不明白如何提供原產地信息到geom_rect。 有什麼問題?

回答

1

如果您從aes調用中刪除最小和最大參數,您的繪圖應呈現正確。這裏有一個例子一些玩具數據:

# Create made up data 
data <- data.frame(time = seq(1, 10, by = 1), 
        ert = runif(n = 10)) 

# Turn into date format - added as.Date to origin statement 
data$time<-as.Date(data$time, "%d/%m/%y", origin = as.Date("1970-01-01")) 

# Verify similar structure to OPs dataset 
head(data) 
#   time  ert 
# 1 1970-01-02 0.4485163 
# 2 1970-01-03 0.8100644 
# 3 1970-01-04 0.8123895 
# 4 1970-01-05 0.7943423 
# 5 1970-01-06 0.4398317 
# 6 1970-01-07 0.7544752 

pt1.plot<- ggplot(data, aes(time, ert, group=1, na.rm=T))+ 
    geom_rect(xmin=2, 
       xmax=Inf, ymin=-Inf, ymax=Inf, fill="lightgreen", alpha=0.03) + 
    geom_line()+ 
    labs(x="", y="ert")+ 
    geom_hline(aes(yintercept=0.5), colour="#990000", linetype="dashed") 

pt1.plot 

enter image description here

+0

謝謝,它的工作!有沒有辦法計算出對應某個日期的數字?否則,我將不得不嘗試數字,並與情節的視覺控制。 – Raphus

+0

你可以嘗試'as.numeric(as.Date(「yourdate」,「%d /%m /%y」,origin = as.Date(「1970-01-01」)))' – Craig

+0

回答你的問題,請接受答案來結束這個問題! – Craig

相關問題