Error: Invalid input: date_trans works with objects of class Date only

前端 未结 1 1035
旧巷少年郎
旧巷少年郎 2020-12-16 12:27

I have a time series dataset called \"Data\" which contains water elevation data for several wells over many years of sampling dates. The head of the data.frame looks like t

相关标签:
1条回答
  • 2020-12-16 12:50

    The problem seems to be in your geom_rect area (it plots without this). Other "date_trans" errors on this site point to needed to set dates with as.Date. So yes, you were in the right debug area. This works:

    Wrap your minimum and maximum in xmin and xmax call in geom_rect section:

    aes(xmin = as.Date("2004-04-29", "%Y-%m-%d"), 
        xmax = as.Date("2004-12-20",  "%Y-%m-%d"),
    

    CODE BELOW FOR OTHERS TO USE

    I created three data lines only as @YourEconProf suggested.

    #Import and fix up data
    #Data = read.csv("water_elevation_for_R_date.csv", stringsAsFactors=FALSE)
    #Date            Well   Elev
    #1    2002-05-23            MW-3 929.04
    #2    2002-05-29            MW-3 929.39
    #3    2002-05-31            MW-3 929.37
    # etc...
    Data = data.frame(Date = c(as.Date("2002-05-23", "%Y-%m-%d"),
                               as.Date("2002-05-29", "%Y-%m-%d"),
                               as.Date("2002-05-31", "%Y-%m-%d")),
                      Well = c("MW-3","MW-3","MW-3"),
                      Elev = c(929.04, 929.39, 929.37))
    
    colnames(Data)[1] <- "Date"
    Data$Date = as.Date(Data$Date, format = "%m/%d/%Y")
    Data$Well <- as.factor(Data$Well)
    Data$Elev <- as.numeric(Data$Elev)
    
    #Load ggplot and scales
    library(ggplot2)
    library(scales)
    
    #Create graph
    ggplot(data= Data, aes(x = Date, y = Elev, group = Well, colour = Well)) +
      geom_line(size = 0.75) +
      xlab("") + ylab("Elevation (ft.)") +
      scale_color_brewer(palette = "Spectral") +
      scale_x_date(breaks = date_breaks("2 year"),
                   labels = date_format("%Y")) +
      theme_bw()+
      theme(plot.background = element_blank(), 
            panel.grid.major = element_blank(), 
            panel.grid.minor = element_blank(), 
            panel.border = element_blank(), 
            axis.line.x = element_line(color = "black"),
            axis.line.y = element_line(color = "black")) +
      geom_rect(data = Data, 
                aes(xmin = as.Date("2004-04-29", "%Y-%m-%d"), 
                    xmax = as.Date("2004-12-20",  "%Y-%m-%d"),
                    ymin = -Inf, 
                    ymax = Inf),
                fill = "gray", 
                alpha = 0.5)
    

    Which gets you this:

    0 讨论(0)
提交回复
热议问题